简体   繁体   English

React Redux(不是)从 mysql db 更新数组的状态

[英]React Redux (is not) updating the state of an array from mysql db

This is my first react project and first JS project overall so I am incredibly new to the language though I have some prior experience with c#.这是我的第一个 react 项目,也是第一个 JS 项目,所以我对这门语言非常陌生,尽管我有一些 c# 的经验。

I got my app to a working version locally but my states and prop passing was getting out of hand so I wanted to implement redux before it gets worse.我让我的应用程序在本地工作了一个版本,但我的状态和道具传递已经失控,所以我想在它变得更糟之前实施 redux。 I have a getClients Axios function that seems to work with a local state but something about the way its set up isn't working for redux.我有一个 getClients Axios 函数,它似乎适用于本地状态,但它的设置方式不适用于 redux。 I set up console logs and debuggers and it looks like the reducer is seeing the action.payload just fine and should be updating the state.我设置了控制台日志和调试器,看起来减速器看到 action.payload 很好,应该更新状态。 but my clientList variable with useSelector is always showing an empty array.但是我的带有 useSelector 的 clientList 变量总是显示一个空数组。

 export default function ClientDisplay() { // const [clients, setClients] = useState([]); const clientList = useSelector((state) => state.clientList); const dispatch = useDispatch(); useEffect(() => { getClients(); console.log("initial load"); }, []); const getClients = () => { Axios.get("http://localhost:3001/table/clients").then((response) => { console.log("getClients trigered") dispatch(setClientList(response.data)); }); };

 import { createSlice } from "@reduxjs/toolkit" export const clientListSlice = createSlice({ name: 'ClientList', initialState: [], reducers: { setClientList(state, action) { state = action.payload; }, }, }); export const {setClientList} = clientListSlice.actions export default clientListSlice.reducer;

 const store = configureStore({ reducer : { activeClient: activeClientReducer, clientList: clientListReducer, }, }) const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <Provider store={store}> <App /> </Provider> );

Try defining the initialState properly.尝试正确定义 initialState。

export const clientListSlice = createSlice({
    name: 'clientList',
    initialState: {clients:[]},
    reducers: {
        setClientList(state, action) {
            state.clients = action.payload;
        },
    },
})

and then in useSelector然后在 useSelector

const {clients} = useSelector((state) => state.clientList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM