I have simple input which will be available in two different components so to share the state of this input, I decided to use reducer.
Here is my solution:
index.js
.....
const Index = () => {
const store = createStore(rootReducer, applyMiddleware(thunk));
.............
Reducer
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
here is my component
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
Unfortunately, I get the following error.
Error: Actions must be plain objects. Use custom middleware for async actions.
What am I doing wrong here? thx
setName
is your setter for your local react state and has nothing to do with redux - so it's result cannot be dispatched. You will need to write an action creator instead.
Generally, useState
is local component state. So it also does not select the value from the redux store in any way, which will be your next problem. You will need to use useSelector
instead.
Also, you are using a very outdated style of redux here which we do not really recommend any more. To learn modern redux, please follow the official tutorials over at https://redux.js.org/tutorials/index - you will write a lot less and more secure code in the end.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.