reactjs 为什么我在尝试订阅状态时返回undefined

dgiusagp  于 2023-05-06  发布在  React
关注(0)|答案(1)|浏览(202)

当使用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>
    ```
xuo3flqw

xuo3flqw1#

我在这里看不到的是ReduxconfigureStore函数。在store/index.js文件中添加:

import { configureStore } from "@reduxjs/toolkit";
import amountAndProviderReducer from "./your_local_path_to_amountAndProviderReducer"

const store = configureStore({
  reducer: { amountAndProvider: amountAndProviderReducer }
});

export default store

在您的Table组件所在的文件中,使用state.amountAndProvider代替state.amountAndProviderReducer

相关问题