Populate value in input field directly from redux

2019-09-20 06:04发布

问题:

Can I set my input fields value to redux store value? Or may I need to copy the props to my local state for this?

<input
      placeholder={props.placeholder}
      value={props.value}
 />

props.value is coming from react-redux's Connect.

But I can't change the value of input, I think this is because props is read only

回答1:

You can set value that way, it's correct. To change such input value you have to add onChange event handler that will dispatch an action updating corresponding value in Redux store (check React doc about controlled form fields):

<input
      placeholder={props.placeholder}
      onChange={(event) => props.updateValueInRedux(event.target.value)}
      value={props.value}
 />

In above example the updateValueInRedux should be a function passed to component from Redux connect as property of mapDispatchToProps argument that will dispatch an action updating Redux state. It should look like that:

const mapStateToProps = {
    ...
}

const mapDispatchToProps = (dispatch) => {
    return {
        updateValueInRedux: (value) => {
            dispatch(someReduxUpdateAction(value));
        }
    }
};

const MyConnectedComponent = connect(
    mapStateToProps,
    mapDispatchToProps
)(MyComponent);


回答2:

To add to what Bartek said, your action could look like this:

//Action Creator
export const UPDATE_VALUE = 'UPDATE_VALUE';

export function updateValueInRedux(value) {
  return ({
    type: UPDATE_VALUE,
    payload: value
  });
}

//Reducer
import {
  UPDATE_VALUE
} from './actions'; //[Or directory where your actions reside]

const INITIAL_STATE = {
  value: ''
}
export default
const UpdaterReducer = (state = INITIAL_STATE, action) {
  switch (action.type) {
    case UPDATE_VALUE:
      return { ...state,
        value: action.payload
      }
    default:
      return state;
  }
}

//Now 'value' will be available to all components that have the reducer state mapped to their properties



标签: reactjs redux