首页 > 解决方案 > 在 React Redux 中使用 Input

问题描述

我有一个简单的输入,可以在两个不同的组件中使用,所以为了共享这个输入的状态,我决定使用 reducer。

这是我的解决方案:

index.js
.....
const Index = () => {
    const store = createStore(rootReducer, applyMiddleware(thunk));
.............

减速器

const initialState = {
    inputValue: "Testing.com"
}

const nameReducerr = (state = initialState, action) => {
    switch (action.type) {
        case "INPUT_CHANGE":
            return Object.assign({}, state, {inputValue: action.text})
        default:
            return state
    }
}

export default nameReducerr

这是我的组件

import React, {useState} from 'react'
import {useSelector, useDispatch } from "react-redux"

function inputData() {
    const [name, setName] = useState('');
    const inputValue = useSelector(state => state.inputValue);
    const dispatch = useDispatch();

    const handleKeyDown = (event) => {
        if (event.key === "Enter") {
          dispatch(setName(event.target.value));
        }
      };
    
      console.log('input value', inputValue);
    return (
        <div>
                <input
                    onKeyDown={handleKeyDown}
                    type="text"
                    className="form-control address"
                    name=""
                  />
                  <h1>Name: {name}</h1>
                  <h1>Input Value: {inputValue}</h1>
        </div>
    )
}

export default input data

不幸的是,我收到以下错误。

Error: Actions must be plain objects. Use custom middleware for async actions.

我在这里做错了什么?谢谢

标签: javascriptreactjsreduxreact-reduxreact-hooks

解决方案


setName是你本地反应状态的设置器,与 redux 无关 - 所以它的结果不能被调度。您将需要编写一个动作创建器。

通常,useState是本地组件状态。所以它也不会以任何方式从 redux 存储中选择值,这将是你的下一个问题。您将需要useSelector改用。

此外,您在这里使用了一种非常过时的 redux 风格,我们不再推荐。要学习现代 redux,请按照https://redux.js.org/tutorials/index上的官方教程进行操作 - 最后您将编写更少且更安全的代码。


推荐阅读