Populate value in input field directly from redux store

你离开我真会死。 提交于 2019-12-12 05:24:51

问题


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


来源:https://stackoverflow.com/questions/44116291/populate-value-in-input-field-directly-from-redux-store

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!