【问题标题】:How to use Fetch API data in Redux如何在 Redux 中使用 Fetch API 数据
【发布时间】:2022-01-04 15:08:13
【问题描述】:

如何使用 redux 从 MongoDB 获取数据以及如何将数据发送到多个页面。如何设置状态以检查数据是否从 redux 获取。

【问题讨论】:

  • 不能直接从 mongoDb 获取数据。您必须查询一个 api 女巫查询数据库。您通常在调度操作时这样做。
  • 请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。

标签: reactjs redux


【解决方案1】:

这里是完整的代码sn-p:

const initialState = {
  allData: [],
};

// Your API Fetch Here
export const fetchData = createAsyncThunk("data/fetchData", async()=>{
  const response = await fetch("http://www.api.com/api")
      .then(res=>res.json())
  return response;
})

export const serviceSlice = createSlice({
  name: 'dataName',
  initialState,
  // The `reducers` field lets us define reducers and generate associated actions
  reducers: {
    
  },

  extraReducers: (builder) => {
      // data goes into state
    builder.addCase(fetchData.pending, (state) => {
        state.status = 'loading';
      })
    builder.addCase(fetchData.fulfilled, (state, action) => {
        state.status = 'idle';
        state.allData.push(action.payload) ;
      });
  },
});

【讨论】:

    猜你喜欢
    • 2018-01-16
    • 2017-09-23
    • 2017-04-08
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多