如何设置状态以从APi答复

Paw*_*ski -1 javascript setstate reactjs

我试图设置状态以响应Api onClick。状态获得更新,但是当我第一次单击时没有更新,第二次单击是的,它的确更新了。

     fetch(URL)
          .then(res => res.json())
          .then(res => {
            this.setState({
              recipesList: res
            });
          });
    console.log(this.state.recipesList);


  };
Run Code Online (Sandbox Code Playgroud)

有人能帮我吗 ?

k3l*_*dev 5

setState()是异步的。这意味着React会选择何时才是更新状态的正确时间,而这可能并非您正在执行的时间console.log()

console.log()setState回调函数上使用,因此当状态更改时,将执行您的函数:

fetch(URL)
   .then(res => res.json())
   .then(res => {
       this.setState({
          recipesList: res
       },()=>{//setState callback.
          console.log(this.state.recipesList);
       });
    });
Run Code Online (Sandbox Code Playgroud)

在componentWillMount()中使用获取函数

这是由于ReactJS生命周期。如果您在内部执行该函数componentWillMount,则不会导致第二次渲染

class yourComponent extends React.Component{

  state = {
     recipesList: []
  }

  componentWillMount(){
    fetch(URL)
     .then(res => res.json())
     .then(res => {
         this.setState({
            recipesList: res
         },()=>{//setState callback.
            console.log(this.state.recipesList);
         });
      });
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您fetch在内部使用过componentWillMount(),则可以:

从地图直接渲染到渲染。

在渲染方法中,使用map函数,如下所示:

render(){
    return (
      <div className="App">
        <div className="contentWrapper">
          {
             this.state.recipesList.map(item => {
               return (
                  <div className="recispesList">
                     <h1>{item.title}</h1>
                  </div>
               );
             })
          }
        </div>
      </div>
    );
}
Run Code Online (Sandbox Code Playgroud)