当使用useSelector钩子时,我的状态被返回为undefined。
我有一个简单的应用程序,需要一个提供商的名称和总金额支付给提供商。
AmountAndProvider接受这些值作为输入,单击时将分派数据。
当试图获取表组件中的状态时,状态是否未定义?
const AmountAndProvider = () => {
const dispatch = useDispatch();
const [amountAndProviderEntry, setAmountAndProviderEntry] = useState({
provider: "",
amount: "",
});
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setAmountAndProviderEntry({
...amountAndProviderEntry,
[name]: value,
});
};
const onClick = () => {
console.log(amountAndProviderEntry);
dispatch(setAmount(amountAndProviderEntry.amount));
dispatch(setProvider(amountAndProviderEntry.provider));
};
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
amount: 0,
provider: "",
};
export const amountAndProviderReducer = createSlice({
name: "amountAndProviderReducer",
initialState,
reducers: {
setAmount: (state, action) => {
state.amount = action.payload;
},
setProvider: (state, action) => {
state.provider = action.payload;
},
},
});
export const { setAmount, setProvider } = amountAndProviderReducer.actions;
export default amountAndProviderReducer.reducer;
<Provider store={store}>
<App />
</Provider>
const App = () => (
<>
<AmountAndProvider />
<Table />
</>
);
const Table = () => {
const state = useSelector((state) => state.amountAndProviderReducer);
return (
<table>
<thead>
<tr>
<th>Provider</th>
<th>Amount</th>
</tr>
</thead>
```
1条答案
按热度按时间xuo3flqw1#
我在这里看不到的是ReduxconfigureStore函数。在store/index.js文件中添加:
在您的Table组件所在的文件中,使用state.amountAndProvider代替state.amountAndProviderReducer