我正在try 学习AXIOS异步方法的Reaction-Redux的用法,我使用useEffect
钩子调用异步函数并调度操作来存储数据并将数据分配给状态,但运行后无法获得状态.我确实从API获得了数据,只是没有分配给channel
状态,也没有呈现.
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './modules/counterStore';
import channelReducer from './modules/channelStore';
// create store with reducer
const store = configureStore({
reducer: {
channel: channelReducer,
},
});
export default store;
import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const channelStore = createSlice({
name: "channelStore",
initialState: {
channel: [],
},
reducers: {
setChannel: (state, action) => {
state.channel = action.payload;
},
},
});
const { setChannel } = channelStore.actions;
const channelReducer = channelStore.reducer;
const fetchChannelList = () => {
return async (dispatch) => {
await axios.get("http://geek.itheima.net/v1_0/channels").then(
(res) => {
dispatch(setChannel(res.data.data.channels))
console.log(res.data.data.channels)
}
);
};
}
export { fetchChannelList };
export default channelReducer;
import './App.css';
import { useSelector, useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { fetchChannelList } from './store/modules/channelStore';
function App() {
const { channelList } = useSelector(state => state.channel)
const dispatch = useDispatch()
useEffect(() => {
dispatch(fetchChannelList())
}, [dispatch])
return (
<div >
<ul>
{channelList?.map(item => {
return (<li key={item.id}>{item.name}</li>)
})}
</ul>
</div>
);
}
export default App;
我试图从API获取数据,并使用分派操作将数据分配给状态并呈现在页面中.