This is my input
<input
type="text"
onChange={(e) => {
props.setInputVal(e.target.value);
}}
/>
This is the action file
export const setInputVal = (val) => {
return {
type: SET_INPUT,
payload: val
};
};
This is the state I want to set input's value to in redux reducer
const initialState = {
inputVal: ''
};
export const reducer = (state = initialState, action) => {
switch (action.type) {
case SET_INPUT:
return {
inputVal: [ action.payload ]
};
default:
return state;
}
};
But I'm getting the an error so How can I properly set the input value when user types in to the inputVal state in redux reducer?
You should read Using Redux with React . Pay close attention to the mapStateToProps()
function and how it is used with the connect()
higher-order component.
I guess the error you get has to do with the fact that inputVal
becomes an array instead of string on SET_INPUT
action dispatch. Fix your reducer as follows:
export const reducer = (state = initialState, action) => {
switch (action.type) {
case SET_INPUT:
return {
...state,
inputVal: action.payload
};
default:
return state;
}
};
You also have to connect inputVal
to input value using connect()
function:
<input type="text" value={props.inputVal} {...} />
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.