我在 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)
}
答案 0 :(得分:0)
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.