Redux-React使用api调用填充initialState

时间:2019-12-06 14:35:30

标签: reactjs redux react-redux

使用来自组件或此处的json api调用填充我的initialState

const initialState = {
      myvalues: [] ---->here i want to populate this array
    };

const reducer = (state = initialState, action) => {
  const newState = { ...state };
  switch (action.type) {
    case "Update":
      console.log(newState);
    // newState.myvalues = action.key.title.value;
    default:
      return newState;
  }
};
export default reducer;

2 个答案:

答案 0 :(得分:0)

您可以这样做:

const reducer = (state = initialState, action) => {
  switch (action.type) {
    case "Update":
      return { ...state, myvalues: action.payload }
    default:
      return state;
  }
};

当您分发它时,应该将您的API数据放入payload

答案 1 :(得分:0)

要使用来自API的数据填充initialState,您可以创建例如FETCH_INIT_DATA_ACTION,将在初始化商店后立即将其发送出去。

// ...
const store = createStore(/* ... */)

store.dispatch({ type: 'FETCH_INIT_DATA_ACTION' })

// ...

FETCH_INIT_DATA_ACTION会触发redux-thunk,传奇,效果或您要使用的任何东西。