簡體   English   中英

Redux狀態已更新,但未更新組件

[英]Redux state is updated but not the component

我在存儲和狀態更新后更新/重新呈現組件時遇到問題。

1-在頁面加載時,創建的商店的初始狀態為空,因此所有組件均以空白狀態呈現

 store = createStore(Reducers, {}, compose(applyMiddleware(...middleware, thunk), extension)); 

2-然后從API提取數據,並用該數據調度操作。

 axios.get(url).then(res => {
  store.dispatch(getFromServer(res.data));
 })

3-狀態在這里是一個對象,對象的鍵是化器以及組件和化簡器通過CombineReducers進行組合。 因此,在分派getFromServer動作時,它將在所有化簡器中偵聽。並在相應的化簡器中更新狀態對象。化簡器示例如下。

  import update from 'immutability-helper';
  import * as types from '../actions/constants';
  const initialState = {};
  export default (state = initialState, action) => {
     switch (action.type) {
       case types.GET_FROM_SERVER:
        return update(state,{
            $set:action.schema.database
        })
    case types.SAVE_NAME:
        return { name: action.name };
    default:
        return state;
  }
 };

現在我可以看到一開始我的組件處於空狀態,然后狀態被正確更新。組件代碼如下:

 import React, { Component } from 'react';
 import { observable } from 'mobx';
 import { observer } from 'mobx-react';
 import Table from '../containers/Table';
 @observer class Tables extends Component {'
   props: Props
   constructor(props) {
    super(props);
    this.state = { tables : { }  }
}
componentWillMount(){
    this.setState({
        tables : this.props.tables
    })
}
componentWillReceiveProps(nextProps){
    this.setState({
        tables : this.props.tables
    })
}   

render() {
    var {tables} = this.props;
    console.log(tables);
    return (
        <div className='table-wrapper'>
            { tables.map((table) => (
                <div key={ table.id }>{
                <Table
                    key={ table.id }
                    data={ table }                        
                />)</div>
            ))}                
        </div>
    );
}
}

type Props = {
  tables: Array<TableType>    
};

export default Tables;

我可以在瀏覽器控制台中查看狀態更改。

在此處輸入圖片說明

上一個狀態和下一個狀態顯示狀態更新。

還顯示此this.props.data正在更新的render方法,但此處的視圖仍未更新。

我在這里提到的狀態更新時做錯了嗎?

您正在使用componentWillReceiveProps生命周期掛鈎來捕獲從props更新組件的時刻:

componentWillReceiveProps(nextProps){
    this.setState({
        tables : this.props.tables
    })
}   

但是,我很確定你想用新的道具來更新狀態

componentWillReceiveProps(nextProps){
  this.setState({
     tables : nextProps.tables
  })
} 

您提取tablesthis.props ,從提取它this.state所以它會在更新每個渲染。

render() {
  const {tables} = this.state;

另一件事,您map()表,所以我假設它是一個數組。 因此,您應該使用數組而不是對象來初始化它:

從:

this.state = { tables : { }  }

至:

this.state = { tables : [ ]  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM