[英]What is the best way to implement undo state change (undo store/history implementation) in React Redux
[英]React js, What is the best way to store redux state into local state?
我有tables
減速器,其中一個狀態是mainTables
。 我正在使用react-dnd
來定位這些表。
const initialState = {
channel: null,
errors: null,
mainTables: [],
takeaways: [],
showMainTables: false,
showTakeaways: false,
};
所以現在,我的tables_container
如下所示。
constructor() {
super();
this.state = {
tables: []
}
this.fetchTables = this.fetchTables.bind(this);
this.moveTable = this.moveTable.bind(this);
this.saveTables = this.saveTables.bind(this);
}
componentDidMount(){
this.fetchTables()
}
fetchTables () {
httpGet('/api/v1/tables')
.then((response) => {
this.setState({
tables: response.main_tables
});
});
};
table_container
是一個表的容器,用戶可以通過drag and drop
移動table
來定位它。 雖然我在reducer中有mainTables
存儲mainTable
所有對象, mainTable
我使用fetchTables
將main_tables
存儲到tables
本地狀態,因為我希望用戶移動表進行測試,然后如果他們喜歡它們,他們可以通過單擊save
按鈕來存儲它。 如果他們不喜歡它,他們就可以離開頁面。 因此,當用戶移動表時,它不必一直改變redux狀態。 但是用這種方法存在問題。 當我在componentDidMount
使用fetchTable()
時,它不會在用戶創建表時更新this.state.tables
。 所以要查看剛剛創建的表,用戶必須刷新頁面..
那么,我想問的是1)如何將redux狀態存儲到本地狀態( this.state
)並在更新redux狀態時更新? 可能嗎? 2)創建新表時可以調用fetchTables
嗎? 如何?
提前致謝..
----編輯添加渲染方法
render() {
if (this.props.tables.showMainTables ==true){
const { hideSourceOnDrag, connectDropTarget, number } = this.props;
const { tables } = this.state;
return connectDropTarget(
<div style={styles}>
{Object.keys(tables).map((key) => {
const { x, y, number } = tables[key];
return (
<Table
key={key}
id={key}
x={x}
y={y}
number={number}>
</Table>
);
})}
<button onClick={this.saveTables}>Save</button>
</div>,
);
}
else return false;
}
通常,您需要創建一個商店,例如TablesStore,它將包含初始狀態以及任何外部操作(即網絡調用發生)之后的任何后續狀態。
您的組件將訂閱它。 每次狀態發生變化時,商店都會讓您的組件知道。 然后你可以簡單地執行類似this.setState(TablesStore.getTablesState())
不鼓勵從您的組件發送提取請求。 此外,如果您正在尋找一個完整的架構來建立您的應用程序,我不認為這是最好的地方,因為這將很容易變得足夠長的教程。
我使用contructor(props)
和componentWillReceiveProps
將全局狀態存儲到本地狀態。
所以在視圖中,我創建了const mainTable = this.props.tables.mainTables
並將mainTable
傳遞給table_container
。
constructor(props) {
super(props);
this.state = {
tables: props.mainTables
}
}
並制作了如上所述的構造函數。 為了獲取更新的數據並將其更新到本地狀態,我使用了componentWillReceiveProps
componentWillReceiveProps(nextProps){
if(this.state.tables.length != nextProps.mainTables.length){
this.setState({tables: nextProps.mainTables})
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.