代码之家  ›  专栏  ›  技术社区  ›  Deadpool

从服务文件发送的数据在Reducer状态下未更新

  •  0
  • Deadpool  · 技术社区  · 6 年前

    我好像遇到了一个奇怪的问题。问题是我正在尝试创建一个API命中(在服务文件中),它反过来提供一些数据(它正在工作),这个数据将在我的 reducer1.js

    减速器1.js ,为什么更新后的状态不会由“GET_List”操作类型返回?有人能看出什么问题吗?

    const global = {
      getActressList: async function(){
        const response = await fetch("http://localhost:2000/api/actressList");
        const data = await response.json();
        return data;
      }
    }
    
    export default global;
    

    减速器1.js

    import global from '../../services/index';
    
    const initialState = {
      data: [
        {
          id: 1, 
          name: "Aishwarya Rai",
          src: "/assets/img/aishwarya.png"
        }
      ]
    };
    
    function reducer1(state = initialState, action) {
    
      switch (action.type) {
    
        case "GET_LIST": {
          const data = global.getActressList();
          data.then((res)=> {
            return {
              ...state,
              data: res
            }
          })
        }
        default:
          return state;
      }
    }
    
    export default reducer1;
    

    结果:

    enter image description here

    1 回复  |  直到 6 年前
        1
  •  1
  •   Rostyslav    6 年前

    您是从一个承诺中返回,而不是从reducer函数返回:

    function reducer1(state = initialState, action) {
      switch (action.type) {
        case "GET_LIST": {
          const data = global.getActressList();
          data.then((res) => {
            // here you are returning from a promise not from a reducer function
            return {
              ...state,
              data: res,
            };
          });
        }
        default:
          return state;
      }
    }
    

    reducer中的代码应该是这样同步的:

    function reducer1(state = initialState, action) {
      switch (action.type) {
        case "GET_LIST": {
          return {
            ...state,
            data: action.payload,
          };
        }
        default:
          return state;
      }
    }
    

    function YourComponent() {
      const dispatch = useDispatch();
      const data = useSelector(state => state.data)
    
      useEffect(() => {
        const data = global.getActressList();
        data.then((res) => {
          dispatch({type: 'GET_LIST', payload: res});
        });
      }, [])
    
      ...
    }
    

    编辑

    componentDidMount 像这样的生命周期挂钩:

    class YourComponent extends Component {
      state = { data: [] };
    
      componentDidMount() {
        const data = global.getActressList();
        data.then((res) => {
          dispatchYourAction({type: 'GET_LIST', payload: res});
        });
      }
    
      ...
    }