首页 > 解决方案 > 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]);

标签: javascriptreactjsreact-hooksuse-reducer

解决方案


推荐阅读