将变量设置为等于状态会在变量更改时更新状态
Setting a variable equal to a state updates the state on variable change
我最终想创建状态的副本,相应地更新它而不重新渲染然后 setState(myCopy) 触发视图更新。这个问题通过代码更好的解释:
export default function App() {
// Table Data
const [tableState, setTableState] = useState({
tableHead: ['Currency', 'Sell', 'Buy'],
tableData: [
['USD', '1', '1'],
['EUR', '2', '2'],
['JPY', '3', '3'],
],
});
var newTableState = tableState;
useState(() => {
let rate1 = 15;
let rate2 = 8;
// * These 2 lines:
newTableState.tableData[0][1] = rate1;
newTableState.tableData[0][2] = rate2;
},[])
return(
<View>
<Text>{tableState.tableData[0][1]}</Text>
<Text>{tableState.tableData[0][2]}</Text>
</View>
)
}
这两行应该只更新newTableState。但是,tableState 也会更新,从而更新视图。这是预期的行为吗?
我记得读过不使用 setState 直接更新状态是不好的做法,我认为这里正在这样做。
这是一个demonstrating snack。
发生这种情况是因为您没有分配 tableState 本身,而是分配对它的引用。所以更新 newTableState
意味着你正在改变状态。
有几种方法可以做到这一点,要么使用 lodash
的 cloneDeep
const newTableState = cloneDeep(tableState);
或者像这样使用 JSON
:
const newTableState = JSON.parse(JSON.stringify(tableState));
我最终想创建状态的副本,相应地更新它而不重新渲染然后 setState(myCopy) 触发视图更新。这个问题通过代码更好的解释:
export default function App() {
// Table Data
const [tableState, setTableState] = useState({
tableHead: ['Currency', 'Sell', 'Buy'],
tableData: [
['USD', '1', '1'],
['EUR', '2', '2'],
['JPY', '3', '3'],
],
});
var newTableState = tableState;
useState(() => {
let rate1 = 15;
let rate2 = 8;
// * These 2 lines:
newTableState.tableData[0][1] = rate1;
newTableState.tableData[0][2] = rate2;
},[])
return(
<View>
<Text>{tableState.tableData[0][1]}</Text>
<Text>{tableState.tableData[0][2]}</Text>
</View>
)
}
这两行应该只更新newTableState。但是,tableState 也会更新,从而更新视图。这是预期的行为吗?
我记得读过不使用 setState 直接更新状态是不好的做法,我认为这里正在这样做。
这是一个demonstrating snack。
发生这种情况是因为您没有分配 tableState 本身,而是分配对它的引用。所以更新 newTableState
意味着你正在改变状态。
有几种方法可以做到这一点,要么使用 lodash
的 cloneDeep
const newTableState = cloneDeep(tableState);
或者像这样使用 JSON
:
const newTableState = JSON.parse(JSON.stringify(tableState));