TTT*_*TT2 5 javascript reactjs redux react-redux redux-toolkit
我有一个 React 应用程序,其中使用 redux 设置全局状态,在一个组件中填充表单,并根据输入向同一端点发出 axios 请求,从 redux 获取数据,然后我想重定向到另一个端点组件并根据这个新请求过滤状态。问题是,当我重定向时,会显示 redux 定义的相同状态,而不会显示更新的状态。
\n我的 redux 逻辑是这样的:
\nactionsCreatorproductActions.js
\nimport { fetchProductsStart, fetchProductsSuccess, fetchProductsFailure } from '../slices/productsSlice';\nimport { baseUrl } from '../../shared/baseUrl';\n\nexport const fetchProducts = () => async dispatch => {\n try {\n dispatch(fetchProductsStart());\n const response = await fetch(baseUrl+"products");\n const data = await response.json();\n dispatch(fetchProductsSuccess(data));\n } catch (error) {\n dispatch(fetchProductsFailure(error));\n }\n};\nRun Code Online (Sandbox Code Playgroud)\n切片减速器是productsSlice.js
\nimport { createSlice } from "@reduxjs/toolkit";\n\n\nconst productsSlice = createSlice({\n name: "products",\n initialState: {\n products: [],\n loading: false,\n error: null\n },\n reducers: {\n fetchProductsStart(state) {\n state.loading = true;\n state.error = null;\n },\n fetchProductsSuccess(state, action) {\n state.products = action.payload;\n state.loading = false;\n },\n fetchProductsFailure(state, action) {\n state.error = action.payload;\n state.loading = false;\n }\n }\n});\n\nexport const { fetchProductsStart, fetchProductsSuccess, fetchProductsFailure } = productsSlice.actions;\n\nexport default productsSlice.reducer;\n\nRun Code Online (Sandbox Code Playgroud)\n和我的商店configureStore.js
\nimport { configureStore } from "@reduxjs/toolkit"\nimport productsReducer from "./slices/productsSlice"\nexport const store = configureStore({\n reducer: {\n products: productsReducer\n }\n})\nRun Code Online (Sandbox Code Playgroud)\n我上面在handleSubmit中提到的形式的逻辑是:
\n handleSubmit(event){\n event.preventDefault()\n\n // redirect to the store component with the search criteria\n // the search criteria will be passed as query parameters\n var tipo = this.state.tipo\n var marca = toTitleCase(this.state.marca)\n var linea = this.state.linea\n axios.get(baseUrl+'products' + '/?tipo=' + tipo + '&marca=' + marca + '&linea=' + linea )\n .then((response) => {\n console.log('response.data',response.data)\n\n // here I am using the useNavigate hook to redirect and set the state\n // with the response that is returned with the axios request\n this.props.navigate("/store",{\n state:{\n products:response.data\n }\n });\n \n })\n .catch((error) => {\n console.log(error)\n })\n \n }\nRun Code Online (Sandbox Code Playgroud)\n我如何正确更新我的状态,以便根据从表单输入获得的输入来过滤它?有没有更好的方法来做到这一点,我是 redux 的新手,我可以\xc2\xb4t 弄清楚如何更新状态。
\n编辑:我忘了提及我重定向的组件是一个类组件,我可以\xc2\xb4t 将其更改为功能组件
\nEDIT2:我只能更改逻辑,所以现在我重定向的组件是一个功能组件
\n| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |