我正在创建一个分析应用程序,并希望将企业的行业数据存储在全局状态中。我试图使用Redux加载此数据一次,但似乎无法使用2023年8月发布的最新工具包来获取数据额外的reducer。其他参数的全局状态似乎可以工作,只是不能在分析开始时一次性获取数据并将其存储。API的工作原理与我用postman和其他应用程序测试的一样。当页面第一次加载时,Node服务器会被ping,但函数似乎不会。我甚至不认为额外的reducer函数getIndustryData
可以正确导出。
import { createSlice, createAsyncThunk} from "@reduxjs/toolkit";
import db from '../../components/apis/db'
export const getIndustryData = createAsyncThunk(
'analysis/getIndustryData',
async () => {
//using axios object db in another file to fetch data..
const response = await db.get("/getTable/industries")
//note: response already accounts for data in axios on the server side
const data=response
return data;
}
);
const initialState = {
revenue: 5000000000,
spend: 10000000,
industryData: [],
fetchDataStatus: "",
}
export const analysisSlice = createSlice({
name: 'analysis',
initialState,
reducers: {
update: (state, action) => {
state = action.payload;
},
reset: (state) => {
state = initialState;
},
extraReducers: (builder) => {
builder
.addCase(getIndustryData.pending, (state) => {
state.fetchDataStatus= "pending";
})
.addCase(getIndustryData.fulfilled, (state, action) => {
state.fetchDataStatus= "fulfilled";
state.industryData = action.payload.forEach(item => {
state.industryData.push(item)
})
})
.addCase(getIndustryData.rejected, (state) => {
state.fetchDataStatus= "rejected";
})
}
}
});
export const { update, reset} = analysisSlice.actions;
export default analysisSlice.reducer
字符串
组件
const DataTest = () => {
const analysisParams = useSelector((state) => state.analysis)
const dispatch = useDispatch()
useEffect(() => {
dispatch(getIndustryData)
}, [])
return (
<div style={{ display: "block", width: 300 }}>
<h3>Global paramaters:</h3>
<p>{JSON.stringify(analysisParams)}</p>
<h3>Industry Data:</h3>
<p style={{ padding: 20 }}>
{JSON.stringify(analysisParams.industryData)}
</p>
</div>
)
}
export default DataTest
型
1条答案
按热度按时间kiayqfof1#
你所做的一切都是完美的,但你不应该把
extraReducers
放在reducers
里面,它应该在reducers
外面声明。字符串