javascript - 我怎样才能只使用新设置的状态?

标签 javascript reactjs lifecycle

所以我正在使用 github api,我想使用子组件中状态的数据,但它将一次采用初始状态,并在异步函数完成后使用我设置的数据。 如何仅使用 setState 中的数据?

    fetch('https://api.github.com/search/topics?q=javascript', {
      headers: {
        'Accept': 'application/vnd.github.mercy-preview+json'
      }
    })
    .then(res => res.json())
    .then(json => this.setState({ data: json }));
  }

  render() {
    console.log(this.state);

    return (
      <Router>
        <Header jsTrendingName={this.state.data}/>
        <Switch>
          <Route path="/" exact component={Dashboard} />
          <Route path="/home" component={Home} />
        </Switch>
      </Router>

    )

最佳答案

如果还没有,您需要在组件的 componentDidMount 生命周期中进行 API 调用。

Additionally you should maintain the state of your API call (isFetching flag in your initial state).

...
   getJSData = () => {

   // set isFetching to true before API call is made
   this.setState({ isFetching: true });

   fetch('https://api.github.com/search/topics?q=javascript', {
      headers: {
        'Accept': 'application/vnd.github.mercy-preview+json'
      }
    })
    .then(res => res.json())
    .then(json => this.setState({ data: json }));
  }

  componentDidMount() {
     // Call your API
     this.getJSData();
  }
...

您的初始状态是:

state = {
   isFetching: false,
   data: null
}

然后在render方法中,检查API调用状态:

  render() {
    const { isFetching } = this.state;

    if (isFetching) {
        return <span> Loading ... </span>
    }
    // isFetching is false now since API call is complete.
    console.log(this.state);

    return (
      <Router>
        <Header jsTrendingName={this.state.data}/>
        <Switch>
          <Route path="/" exact component={Dashboard} />
          <Route path="/home" component={Home} />
        </Switch>
      </Router>

    )
}

关于javascript - 我怎样才能只使用新设置的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624767/

相关文章:

javascript - React - TypeError : this. props.courses.map 不是函数

product - 一家拥有成功产品但因不创新而破产的公司?

javascript - 具有 1000 多行的 gridview 的切换/取消切换行的性能问题

javascript - 对文本区域的验证不起作用我该如何调试它

javascript - 我可以将哈巴狗(ex-jade)与 react 框架一起使用吗?

ios - 是否可以从其他应用程序启动应用程序

reactjs - 使用 componentDidUpdate react 上下文

JavaScript 如何将嵌套的 json 对象数据设置为单个嵌套映射

javascript - 重新调整有效 JSON 时调用的 Ajax 错误回调

javascript - 在 React return 语句中使用 && 运算符进行条件渲染