尝试将用户输入从表单存储到 redux,但是通过 useSelector 访问的值始终未定义。
切片组件:
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "userSettings",
initialState: {
interval: 15000,
},
reducers: {
updateInterval: (state, action) => {
state.interval = action.payload
}
},
});
export const { updateInterval } = userSlice.actions;
export const userRefreshInterval = (state) => state.userSettings;
export default userSlice.reducer;
输入表单组件:
import React, { useState } from 'react';
import { Button, Form, FormGroup, Label, Input } from 'reactstrap';
import { useSelector, useDispatch } from 'react-redux'
import {userRefreshInterval, updateInterval} from "./store/userSlice.js";
export default function UserSettingsForm() {
const [refreshInterval, setInterval] = useState("");
const dispatch = useDispatch();
const interval = useSelector(userRefreshInterval);
console.log(interval); // <--- always undefined
const handleSubmit = (e) => {
e.preventDefault();
dispatch(updateInterval(refreshInterval));
};
const handleChangeInterval = (text) => {
setInterval(text);
};
return (
<Form onSubmit={handleSubmit} style={{margin: 10}} inline>
<FormGroup className="mb-2 mr-sm-2 mb-sm-0">
<Label for="refreshInterval" className="mr-sm-2">Refresh Interval:</Label>
<Input type="text" name="refreshInterval" id="refreshInterval" placeholder="interval" onChange={(e) => handleChangeInterval(e.target.value)} />
</FormGroup>
<FormGroup className="mb-2 mr-sm-2 mb-sm-0">
<Label for="roundDecimal" className="mr-sm-2">Round results to decimal:
</Label>
<Input type="text" name="roundDecimal" id="roundDecimal" placeholder="roundDecimal" />
</FormGroup>
<Button>Submit</Button>
</Form>
);
}
按照要求使用 store.js 更新:
import { configureStore } from '@reduxjs/toolkit'
import userReducer from "./userSlice";
export default configureStore({
reducer: {
user: userReducer
}
})
感觉好像错过了一些简单的事情,请帮助确定问题的原因。
我还没有第一次看到你的商店。
尝试这个
export const userRefreshInterval = (state) => state.user;
因为您已将切片器命名为用户。如果你想使用
export const userRefreshInterval = (state) => state.userSettings;
像下面这样配置你的商店
export default configureStore({
reducer: {
userSettings: userReducer
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句