useSelector没有在useDispatch之后给出值



我有一个api,它给我的结果,我可以看到我的控制台上的数据,但我不能得到它在useSelector

import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
import { useNavigate } from "react-router-dom";
const initialState = {
value: [],
status: 'idle',
};
export const fetchEmployeesThunk = createAsyncThunk(
'employeelist/fetchEmployeesThunk',
async () => {
const res = await axios.get('https://localhost:7168/Employee/GetEmployeeList').then(
(result) => result.data
)
return res;
})
export const EmployeeListSlice = createSlice({
name: "employeelist",
initialState: initialState,
reducers: {
initialFetch: (state, action) => {
state.value = action.payload;
},
updateEmployeeList: (state, action) => {
state.value = action.payload;
},
},
extraReducers: (builder) => {
builder
.addCase(fetchEmployeesThunk.pending, (state, action) => {   
state.status = 'idle';
state.value = [];
})
.addCase(fetchEmployeesThunk.fulfilled, (state, action) => {
console.log(action.payload);
state.value = action.payload;
state.status = 'finished';
})
},
});
export const getEmployeeListData = (state) => state.employeelist.value;
export const { updateEmployeeList, initialFetch } = EmployeeListSlice.actions;
export default EmployeeListSlice.reducer;
export function fetchEmployees() {
return async (dispatch) => {
const res = await axios.get('https://localhost:7168/Employee/GetEmployeeList').then(
(result) => result.data
)
dispatch(updateEmployeeList(res));
}
}

正如你所看到的,我尝试使用thunk和创建一个函数并在内部调度数据到一个动作,我能够更新状态,但我无法通过选择器获得值,我有一个表,它接受数组

export default function HomePage() {
const dispatch = useDispatch();
const [tempRows, setTempRows] = useState(useSelector((state) => state.employeelist.value));
const [rows, setTableRows] = useState(useSelector((state) => state.employeelist.value));
useEffect(() => {
//dispatch(fetchEmployees());
dispatch(fetchEmployeesThunk());
}, rows);
}

这给了我一个空数组,但是如果我改变了一些东西然后像热加载一样重新加载它现在返回数据,任何帮助都将非常感谢

请照做

const rows = useSelector((state) => state.employeelist.value)

const [rows, setTableRows] = useState(useSelector((state) => state.employeelist.value));

后者意味着"使用从Redux存储中初始化的本地状态"。它只会在setTableRows被调用时改变,而不会在Redux存储改变时改变。

相关内容

  • 没有找到相关文章

最新更新