javascript - 获取后 React setState() 不重新渲染

标签 javascript reactjs fetch setstate

我正在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/

相关文章:

ios - NSUrlConnection 未通过后台获取调用

javascript - Promise.all() 和捕获错误

javascript - 将字符串数组拆分为两个数组,每个数组包含原始字符串的一部分

javascript - 如何根据是否存在更新的文档来删除 Mongodb 中的文档

reactjs - 如何在 React 中导入子组件?

javascript - 在同构应用程序上 react 路由器 redux 初始状态设置

reactjs - 从 fetch 中获取数据而不是将其存储在状态中

javascript - 输入框在 backspace/del 上不能正常工作

javascript - 如何统计 Bing map 中的大量图钉?

javascript - React ES6 类转换不工作