【问题标题】:How to setState to answer from APi如何 setState 从 APi 回答
【发布时间】:2019-05-29 19:28:35
【问题描述】:

我正在尝试将 setState 设置为来自 Api onClick 的响应。状态有更新,但我第一次点击时没有更新,第二次点击,是的,它确实更新了。

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


  };

有人可以帮助我吗?

【问题讨论】:

  • fetch 是异步的,您的 console.log 语句在 fetch 甚至返回之前被调用。将console.log 放在.then 中。但要小心 setState 也是异步的!在 setState 中添加一个回调,然后将您的 console.log 放入其中
  • 您的第一个问题已得到解答。尽量不要在另一个问题中编辑。请再问一个新问题
  • 我现在可以做吗?抱歉,我在 stackoverflow 中很新

标签: javascript reactjs setstate


【解决方案1】:

setState() 是异步的。这意味着 React 将选择何时是更新状态的正确时间,而这可能不是你在做 console.log() 的时候。

setState 回调上使用console.log(),这样当状态改变时,你的函数就会被执行:

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

在componentWillMount()中使用fetch函数

这是由于 ReactJS 生命周期。如果你在componentWillMount 中执行函数,它不会导致第二个render

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);
         });
      });
   }
}

编辑:

如果您在componentWillMount() 中使用了fetch,您可以:

从地图直接渲染到渲染。

在你的渲染方法中,像这样使用地图函数:

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

【讨论】:

  • 它是这样工作的,console.log 显示更新的状态,但现在我想映射 this.state。 recipesList 但我不能,因为状态仍未更新。
  • @PawełDoliński 你应该把它包含在你的问题中。当您这样做时,请随时在此处再次编辑和评论,以便我收到通知并为您提供更准确的答案。
  • 现在好点了吗?
  • @PawełDoliński 也编辑了我的答案。看看并告诉我这是否完全解决了您的问题。
  • 我将添加另一个问题,因为我不太清楚我要做什么
【解决方案2】:

您没有提供完整的代码,但从这篇文章中我看到 console.log(this.state.recipesList); 在承诺链之外。

因为fetch() 是异步的,而不是console.log(this.state.recipesList); 会在之前执行 this.setState({ recipesList: res });

将您的console.log() 放入this.setState() 的回调中,该回调将在状态更新后执行。

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

【讨论】:

  • this.setState 也是异步的,所以这可能行不通。
猜你喜欢
  • 1970-01-01
  • 2011-11-21
  • 1970-01-01
  • 2014-10-23
  • 2022-12-03
  • 2012-10-02
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多