在React中渲染对象数组

问题描述 投票:0回答:4

我在React组件中有一个方法,它从API中获取一些数据

this.state.matches首先返回一个空数组

loadMatches() {
    let matches = this.state.matches;
    forEach(this.state.matchIds.splice(0,5), matchid => {
        axios.get(url)
            .then(function (response) {
                matches.push(response.data)
            })
    });
    this.setState({
        matches
    })
}

然后是一个应该将数据映射到React组件的方法

renderMatch() {
    return this.state.matches.map((match, index) => {
        return (
            <Match
                key={index}
                gameId={match.gameId}
            />
        );
    });
}

renderMatch()在我的渲染方法中使用{this.renderMatch()}调用但是没有任何东西被渲染,如果我调用.length它只返回0,即使我可以在devtools中看到该数组包含5个对象。数组中的硬编码对象将被渲染

javascript reactjs
4个回答
4
投票

您正在改变状态,因此React不会触发新的渲染。您应该创建一个新数组而不是推入状态:

loadMatches() {
    let promises = []; 
    forEach(this.state.matchIds.splice(0,5), matchid => {
        promises.push(axios.get(url).then(res => res.data));
    });
    Promise.all(promises).then(matches => {
        this.setState({
            matches
        });
   });
}

编辑处理异步。


0
投票

axios或fetch是一个异步函数,当你调用this.setState时,匹配仍然是一个空数组,因此没有任何渲染。试试这个。你也试图直接改变国家,这是一个很大的错误。

loadMatches() {
 let matches = this.state.matches;
let newMatches =[];
let requests = forEach(this.state.matchIds.splice(0,5), matchid => {
   return new Promise((resolve) => {
         axios.get(url)
            .then(function (response) {
               newMatches.push(response.data)
           })
      });
    });
   Promise.all(requests).then(() => {
     this.setState({
         matches:newMatches
       }) 

    });
}

0
投票

你有两个主要问题:

第一:

.then(function (response) {
   matches.push(response.data)
})

您不应该直接更改状态,您应该执行不可变更新。

第二:

this.setState({
   matches
})

您正在使用空“匹配”更新状态,此时您的api呼叫响应尚未收到。

所以,你的实现应该是这样的:

loadMatches() {
let matches = this.state.matches;
forEach(this.state.matchIds.splice(0,5), matchid => {
    axios.get(url)
        .then(function (response) {
            const newMatch = response.data;
            this.setState({ matches: [...matches, newMatch]});
            matches.push(response.data)
        })
});
}

在这里您可以从阅读它们中获益:

https://daveceddia.com/immutable-updates-react-redux/

https://reactjs.org/docs/state-and-lifecycle.html


-1
投票

axios.get是一个返回promise的异步函数。它就像你订购了一个比萨饼,并在它交付之前尝试吃它。解决承诺时,您需要执行setState()

axios.get(url)
            .then(function (response) {
                this.setState({matches: [...matches, ...response.data]})
               }
© www.soinside.com 2019 - 2024. All rights reserved.