javascript - 在 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.
我在这里做错了什么?谢谢
解决方案
setName
是你本地反应状态的设置器,与 redux 无关 - 所以它的结果不能被调度。您将需要编写一个动作创建器。
通常,useState
是本地组件状态。所以它也不会以任何方式从 redux 存储中选择值,这将是你的下一个问题。您将需要useSelector
改用。
此外,您在这里使用了一种非常过时的 redux 风格,我们不再推荐。要学习现代 redux,请按照https://redux.js.org/tutorials/index上的官方教程进行操作 - 最后您将编写更少且更安全的代码。
推荐阅读
- python - PyQt5 可拖动图标从列表视图到另一个
- ruby-on-rails - “推送被拒绝,无法编译 Ruby 应用程序”在 herouku 上安装 decdim
- spring-batch - 将 MDC 上下文映射复制到 SimpleAsyncTaskExecutor 的工作线程
- bash - bash读取多个文本文件并设置变量
- excel - 如何在用户窗体的主代码中从列表框中引用变量?
- excel - 是否可以根据另一个单元格中的值来保护/取消保护一个单元格?
- awk - 如何使用 sed 将一条线放在另一条线的前面?
- ansible - 如何在 Cisco 路由器上的 Ansible 中运行 Privilege Exec 命令
- php - 使用 PHP 输出上个月和当前年份
- google-sheets - Sumif 索引和匹配 & 谷歌表