【发布时间】:2021-06-19 23:16:45
【问题描述】:
我有一个简单的输入,可以在两个不同的组件中使用,所以为了共享这个输入的状态,我决定使用 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.
我在这里做错了什么?谢谢
【问题讨论】:
-
您正在调度
SetStateAction(setName) 而不是带有type和text的对象。你想dispatch({ type: 'INPUT_CHANGE', text: event.target.value }) -
嗨兄弟,这给我错误:
input value undefined
标签: javascript reactjs redux react-redux react-hooks