是否可以在状态更改后更改减速器的初始状态并使用它?反应

is it possible to change the initial state of reducer after state changed and use it ? React

我只是想知道是否可以使用 useReducer,因为我在 UseEffect 中使用它 获取的数据 => 状态 => useReducer(..., State)

 const [initialData, setInitialData] = useState({ name: 'ass' });
    const [data, dispatch] = useReducer(apiReducer, initialData);

    const Data2 = useFetch('/qaz')

    useEffect(() => {
        setInitialData(Data2)
    }, [Data2])

    useEffect(() => {
        dispatch({ type: 'Different', payload: 'key' })
    }, [initialData])


export function apiReducer(state, action) {
    switch (action.type) {
        case 'Different':
            return { ...state, key: action.payload };
        default:
            return state
    }
}

reducer 创建后无法更改初始状态。你可以做的是dispatch一个替换整个状态的动作。在 useFetch 挂钩返回其数据后,您可以使用 useEffect 挂钩 dispatch"REPLACE_STATE" 操作。


减速机

export function apiReducer(state, action) {
  switch (action.type) {
    case "REPLACE_STATE":
      return action.playload;
    case "Different":
      return { ...state, key: action.payload };
    default:
      return state;
  }
}

组件

export default function App() {
  const [state, dispatch] = useReducer(apiReducer, { name: "ass" });

  const fetchedData = useFetch("/qaz");

  useEffect(() => {
    if (fetchedData) {
      dispatch({ type: "REPLACE_STATE", payload: fetchedData });
    }
  }, [fetchedData]);

  const doSomething = () => {
    dispatch({ type: "Different", payload: "key" });
  };
...
export default function App() {
  const [state, dispatch] = useReducer(apiReducer, { name: "ass" });
  const [change, setChange] = useState(false)
  const fetchedData = useFetch("/qaz");

  useEffect(() => {
    if (fetchedData) {
      dispatch({ type: "REPLACE_STATE", payload: fetchedData });
      setChange(!change)
    }
  }, [fetchedData]);

  useEffect(() => {
    dispatch({ type: "Different", payload: "key" });
  },[change]);