javascript - useReducer 未同步更新项目数组,渲染延迟
问题描述
一个带有这种行为的视频,我在“A”中单击一次,在“D”中单击一次,或者就像有两种状态,真的很奇怪! https://www.loom.com/share/ba7a97f008b14529b15dca5396174c8c
这是更新描述的操作!
if (action.type === 'description') {
const { payload } = action;
const { description } = payload;
const objIndex = state.findIndex(obj => obj === payload.state);
state[objIndex].description = description;
return [...state];
}
这是所要求的大图,我试图简化为我在描述输入中测试的代码:
//outside component
const reducer = (state, action) => {
if (action.type === 'initialState') {
const { payload } = action;
console.log('state', state);
console.log('payload', payload);
return state.concat(payload);
}
if (action.type === 'description') {
const { payload } = action;
const { description } = payload;
const objIndex = state.findIndex(obj => obj === payload.state);
state[objIndex].description = description;
return [...state];
}
};
//inside component
const [states, dispatch] = useReducer(reducer, []);
function updateInitialState(value) {
dispatch({ type: 'initialState', payload: value });
}
function updateDescription(payload) {
dispatch({ type: 'description', payload });
}
useEffect(() => {
states.forEach(state => {
const descriptionInput = (state.status === undefined || state.status === 'available') && (
<FormInput
name="description"
label="Descrição"
input={
<InputText
value={state.description || ''}
onChange={({ target: { value } }) => {
const payload = { description: value, state };
updateDescription(payload);
}}
placeholder="Descrição"
/>
}
/>
);
const index = states.findIndex(e => e === state);
const updateArray = arrayInputs;
updateArray[index] = [descriptionInput];
setArrayInputs(updateArray);
});
}, [states]);
解决方案
推荐阅读
- javascript - 如何
在javascript中实现? - firebase - 当 Firestore 运行备份时,无法读取未定义的属性“toString”
- java - 线程是如何在内存中执行的?
- node.js - 在 aws.for local 上部署后,表达文件上传出错,它可以成功运行
- excel - 如何手动查找残差/回归 SS 和标准误差
- apache-spark - 编写镶木地板文件时可以重叠分区吗
- python - 在Python中为CSC矩阵中的每一行查找非零条目索引的快速方法
- python - 如何使用人脸识别在 Python 中获取人脸特征的大小?
- openssl - 将 CMS_sign() 与 CMS_CADES 标志一起使用,包括 CAdES 合规性的证书链。我必须使用 CMS_PARTIAL 标志吗?
- flutter - 可以在 controller.stopImageStream 之后重新启动 controller.StartImageStream() 还是有办法暂停