在 redux 存储区更改后 useSelector 未触发

时间:2021-07-26 17:08:09

标签: reactjs redux react-redux

我正在开发一个使用 redux 的应用程序

我想在页面打开时使用useEffect来加载数据并记录要存储的数据

但是当存储中的数据改变时 useSelector 不会改变

我从 api 获取数据并将其分派到 redux 存储并使用 useSelector 获取分派的值。 useEffect 将数据分派到商店,但 useSelector 在更改后不提取值

类别

 const categorys = useSelector(state => state.category.category)

useEffect(() => {
    setLoading(true)
   
    listCategory()
    .then(res => {
        dispatch({
            type: "LIST_CATEGORIES",
            payload: res.data.data
        })
        setLoading(false)
    })
    .catch(err => {
        if (err.response) {
            // Request made and server responded
            toast.error(err.response.data.error)
            toast.error(err.response.data.name)
            toast.error(err.response.data.email)
            toast.error(err.response.data.password)
            toast.error(err.response.data.username)

          } else if (err.request) {
            // The request was made but no response was received
            console.log(err.request);

          } else {
            // Something happened in setting up the request that triggered an Error
            console.log('Error', err.message);

          }
        setLoading(false)
    })
}, [])

减速器

const initialState = {
    category:[
      
    ],
    current: null

}
export const categoryReducer = (state = initialState, action) =>{
    switch(action.type){
        case "LIST_CATEGORIES":
            return {
                ...state,
                ...action.payload
            };

        default:
            return state
    }
};

来自 api 的数据

res.data.data = [{ _id: "ksdj9dsfj", 名称:“监视器”, 描述:“它用于查看系统上的内容” }]

1 个答案:

答案 0 :(得分:1)

问题在于您的更新逻辑与 API 返回的数据结构不匹配。

目前,您具有以下初始状态:

const initialState = {
    category:[],
    current: null
}

以及您的 categoryReducer 中的此逻辑:

return {
  ...state,
  ..action.payload
}

该逻辑只有action.payload 看起来像 {category: []} 时才能正常工作。

但是,您显示从服务器返回的数据如下所示:

[{ _id: "ksdj9dsfj", name: "monitor", description: "It is used to view what is on the system" }]

那不是一个对象,而且里面没有 category 字段。

此处的一个解决方法是将 reducer 逻辑更改为如下所示:

return {
  ...state,
  category: action.payload
}