我有減速器tables
和其中一個州mainTables
。我正在使用react-dnd
來定位這些表格。React js,將redux狀態存儲到本地狀態的最佳方法是什麼?
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
是表,其中用戶可以移動table
通過drag and drop
將它定位的容器。即使我有mainTables
在減速器中存儲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;
}
感謝您的回覆。但我完全不理解你的答案......我想要做的是將'tables'初始狀態的'mainTables'存儲到本地組件的狀態'this.state.tables' ..我將'mainTables'傳遞給本地組件,並試圖在'componentDidMount'和'render'中設置'setState',但它們都不起作用..所以我在尋找如何將'mainTables'存儲到本地組件的狀態。 –
你能告訴我你的渲染方法嗎? –
我剛剛添加了渲染方法.. –