promise 内的 setState 未更新[已关闭]

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

为什么渲染函数不会更新状态?请参阅代码中的注释。 在代码内部我有一个静态注释版本,这可以工作,但是动态函数

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;
reactjs promise fetch-api
2个回答
1
投票

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

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

然后就可以了:-)


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

如果有请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.