我正在componentDidMount()中获取数据(我以我想要的形式获取它们)并且我想将它们保存在组件状态与this.setState。 状态没有改变。
- 我控制台日志显示我已到达调用 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() 方法不会立即更新组件的状态,而是在有状态时更新组件的状态。是多个 setState,它们将被批量一起放入一个 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.
关于javascript - 获取后 React setState() 不重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54804435/