【发布时间】: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)。