【问题标题】:CreateSlice's extraReducer action not updating the stateCreateSlice 的 extraReducer 操作不更新状态
【发布时间】:2021-12-29 21:00:57
【问题描述】:

设置

我正在使用createSlice 编写一个reducer:

export const fetchUserProfile = createAsyncThunk(...)

export const UserProfileSlice = createSlice<UserProfileState | null, SliceCaseReducers<UserProfileState | null>>({
  name: 'UserProfile',
  initialState: null,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(fetchUserProfile.pending, (state, action) => {
      console.log("Fetching user profile...")
    })
    builder.addCase(fetchUserProfile.rejected, (state, action) => {
      // TODO: Handle this properly later.
      console.log('Failed to fetch user profiles: ', action.payload)
    })
    builder.addCase(fetchUserProfile.fulfilled, (state, action) => {
      console.log('State was: ', state)
      state = action.payload
      console.log('State is ', state)
    })
  }
})

export default UserProfileSlice.reducer

我正在使用 combineReducers 将切片的减速器添加到我的根减速器中,并且我正在创建我的商店:

export const store = createStore(rootReducer, applyMiddleware(thunk));

我以这种方式在组件中使用状态:

const user = useAppSelector(state => state.userProfileReducer)

预期行为

fetchUserProfile.fulfilled 动作被调度时,状态被更新并且组件被重新渲染以反映其数据。

实际行为

传递给builder.addCase(fetchUserProfile.fulfilled,...) 的闭包正在运行(如控制台输出所示),但其结果从未反映在组件所看到的状态中。

我是响应原生和整个 JS 生态系统的新手,所以我在调试这个方面有点难过。感谢您的帮助。

【问题讨论】:

    标签: react-native react-redux expo redux-thunk redux-toolkit


    【解决方案1】:

    这是在Writing Immer Reducers: Mutating and Returning State 中处理的。

    state = newValue 没有任何作用。它不会修改state 中的对象,而是丢弃state 中的对象并将一些新值放入变量中

    可以从函数外部观察到处于状态的对象的变化 - 不能简单地更改变量。

    解决方案?

    改为return newValue

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 2022-08-17
      • 2021-03-29
      • 2020-06-12
      • 2019-08-18
      • 2017-12-02
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多