【问题标题】:setState inside promise not updated [closed]承诺内部的setState未更新[关闭]
【发布时间】:2020-01-22 08:14:42
【问题描述】:

为什么渲染函数不会更新状态?请参阅代码中的 cmets。 在代码中,我有一个静态注释版本,这是可行的。但是动态函数 get(..) 不会更新渲染函数的状态。

import React, { Component } from 'react';
import Products from "./components/products";

import './App.css';

//function App() {
class App extends Component {

  state = {
    products: [],
  }

  componentDidMount() {
    const productsURL = 'http://wundp.192.168.43.67.xip.io/rest/products';


    const get = (url, key) => {
      fetch(url)
          .then(res => res.json())
          .then((data) => {
            /* this works and i see the data */
            console.log('1: ', data[key]);

            /* the state is not updated, why?  */
            this.setState({ key : data[key] })
          })
          .catch(console.log)
    }

    /* this fails, the state in the render function is later empty, why?  */
    get(productsURL, 'products');

    /* this works!
    fetch('http://wundp.192.168.43.67.xip.io/rest/products')
        .then(res => res.json())
        .then((data) => {
          console.log(data);
          this.setState({ products: data.products })
        })
        .catch(console.log)
    */
  }

  render() {
    /* this.state.products is empty, why?  */
    console.log('state: ',this.state.products);

    return  (
        <Products products={this.state.products} />
    );
  }

}

export default App;

谢谢你帮助我。

【问题讨论】:

  • 因为你设置的是this.state.key,而不是this.state[key](即this.state.products)。

标签: reactjs api promise fetch


【解决方案1】:

更新状态

state = {
    products: [],
    key: int
}

然后下面的代码可以工作 - this.setState({ key : data[key] }) --> setState 将更新状态中存在的属性。

const get = (url, key) => {
      fetch(url)
          .then(res => res.json())
          .then((data) => {
            this.setState({ key : data[key] })
          })
          .catch(console.log)
    }

如果有请告诉我。

【讨论】:

    【解决方案2】:

    感谢您的反馈。您的解决方案不起作用。 它会给出这个错误,因为我不使用打字稿。 第 13 行:'int' 未定义

    我找到了解决方案,我必须用 [] 包装密钥... this.setState({ [key] : data[key] })

    然后它工作:-)

    【讨论】:

      猜你喜欢
      • 2018-12-02
      • 2015-06-10
      • 1970-01-01
      • 2021-11-08
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 2019-07-23
      相关资源
      最近更新 更多