首页 > 解决方案 > 与 useContext 一起使用时,Usereducer 状态始终未定义

问题描述

我正在尝试将 useReduce 与 一起使用useContext,当我在减速器中控制台值时,我在控制台中获取了一个对象数组,但是当我尝试从另一个组件访问状态时,我得到的状态是未定义的。State.map() 完全是空的。

这是我的代码

应用程序.js

import React, { createContext, useReducer, useEffect } from 'react';

import Uploadproject from './Uploadproject';
import Getprojects, { projectget } from './Getprojects';
import reducer from './reducer/Usereducer';

export const Contextstate = createContext();

const App = () => {
  const initialvalue = null;
  const [state, dispatch] = useReducer(reducer, initialvalue);

  const updatestate = async () => {
    const data = await projectget();
    dispatch({ type: 'add', payload: 'from app.js' });
  };

  useEffect(() => {
    updatestate();
  }, []);

  return (
    <>
      <Contextstate.Provider value={{ state, dispatch }}>
        <Uploadproject />
        <Getprojects />
      </Contextstate.Provider>
    </>
  );
};

export default App;

Usereducer.js

import { projectget } from '../Getprojects';

const reducer = (state, action) => {
  if (action.type === 'add') {
    projectget().then((result) => {
      console.log(result);
      // state = [ ...result]
      state = result;
      console.log(state);
      return state;
    });
  }
};
export default reducer;

获取项目.js

import React, { useContext, useEffect, useState } from 'react';

import { Contextstate } from './App';

const Getprojects = () => {
  const { state, dispatch } = useContext(Contextstate);
  const getstate = () => {
    dispatch({ type: 'add', payload: 'from getprojects' });
  };

  useEffect(() => {
    getstate();
  }, []);

  console.log(state);

  return (
    <>
      <div>
        <h1>Projects</h1>
        {state &&
          state.map((cur) => {
            return (
              <div key={cur._id}>
                <h1>{cur.title}</h1>
                <p>{cur.description}</p>
                <button
                  onClick={() => {
                    deletproject(cur._id);
                  }}
                >
                  Delete
                </button>
              </div>
            );
          })}
      </div>
    </>
  );
};

export default Getprojects;

当我尝试从 Getprojects 组件访问状态时,它的值是未定义的。但是如果我在减速器内部,控制台会得到一个对象数组。在任何其他组件中,状态是未定义的。任何想法???

标签: reactjsreact-reduxreact-hooksuse-contextuse-reducer

解决方案


如果你想使用 redux 在你的应用程序中处理异步逻辑,你应该选择一个Async Redux Middleware

  • redux-thunk(更容易配置,适合小型项目)
  • 还原传奇
  • redux-observable 等

或者您可以只使用useEffect并仅向其发送结果操作。例如:

  useEffect(() => {
    dispatch(getProjectActionStart());
    projectget()
      .then((result) => {
        console.log(result);
        // state = [ ...result]
        state = result;
        console.log(state);

        dispatch(getProjectActionStart(state));
        return state;
      })
      .catch(() => {
        dispatch(getProjectActionFailed());
      });
  }, []);


推荐阅读