[英]React setState() after fetch not rerendering
我正在componentDidMount()中 获取数据( 以所需的形式 获取数据),并希望使用this.setState将它们保存在组件状态中 。 状态没有改变。
const that = this
该组件未重新渲染且状态未更改,我想知道为什么。
我的代码:
export class Offers extends Component {
constructor(props) {
super(props);
this.renderOffer = this.renderOffer.bind(this);
this.state = {
...
};
}
componentWillMount() {
this.setState(() => ({
offer: {},
isLoading: true,
isMyOffer: false,
...
}));
}
componentDidMount() {
console.log('MOUNTED');
const { profile } = this.props;
if (profile) {
this.setState(() => ({
isLoading: false
}));
}
if (profile && profile._id) {
this.setState(() => ({
isMyOffer: true,
...
}));
fetch(`/api/offers-by/${profile._id}`,{
method: 'GET'
})
.then(response => response.json())
.then(offers => {
if(!offers || !offers.length) {
this.setState(() => ({
isLoading: false
})
);
} else {
console.log('ELSE', offers[0]._id); // getting proper data
console.log('THIS', this) // getting this object
const offerData = offers[0]
this.setState(() => ({
offer: offerData,
isLoading: false
})) // then
}}) // fetch
console.log('STATE', this.state)
}
console.log('STATE', this.state)
}
setState有一个回调方法作为第二个参数,您应该在初始setState之后使用它,这是有效的,因为setState本身是一个异步操作。setState()方法不会立即更新组件的状态,而是如果存在多个setStates ,它们将一起批处理到一个setState调用中。
this.setState(() => ({
isLoading: false
}),() =>{
/// You can call setState again here and again use callback and call fetch and invoke setState again..
});
理想情况下,您可以将一些setState重构为单个setState调用。从一个空对象开始,然后根据条件将属性添加到您的对象中。
const updatedState ={}
if(loading){
updatedState.loading = false
}
if(profile &&..){
updatedState.someProperty = value.
}
this.setState(updatedObject,()=> {//code for fetch..
}) // Using the object form since you don't seem to be in need of previous State.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.