首页 > 解决方案 > 在 redux 中更新状态对象的正确方法 react native

问题描述

我做了一个函数来更新 React 中的状态,一个简单的对象。但我不确定这是否是正确的方法,因为它是不可变的。有人可以说是否正确吗?

handleInputChange = (val) =>{
    // here -> some validation
    this.setState({myLimit: newVal})
  }
  submit = () => {
    let lim = {'lim':this.state.myLimit};
    this.props.updateLimit(lim);
  } 
  return (

     <TextInput 
      keyboardType ="numeric"
      autoCorrect={false}
      onChangeText={ this.handleInputChange }
      value={this.state.myLimit} 
     />
)

const mapDispatchToProps = (dispatch) => {
  return {
    updateLimit: (lim) => { dispatch(updateLimit(lim))}
  }
}

const mapStateToProps = (state) => {
  return {
    limit: state.limit,
  }
}

rootReducer.js

const initState = {
  expenses:[
    { key: '1', sum: '100.67'},
    { key: '2', sum: '200.00'},
  ],
  categories: [
    { id:'1', name: 'a' },
    { id:'2', name: 'b' },
  ],
  limit: {lim:'1000'}  //<- this value I need to update
}

const rootReducer = (state = initState, action) => {
  switch(action.type){
    //some cases
    case 'UPDATE_LIMIT': {
      return {
        ...state,
        limit: action.lim
      }
    }
    default:
      return state;
  }
}

export default rootReducer;
export const updateLimit = (lim) => {
  return {
    type: 'UPDATE_LIMIT',
    lim
  }
}

它工作得很好,但我想这里可能有一些错误,因为我直接改变了状态。我将不胜感激任何帮助!

标签: reactjsreduxreact-reduxstate

解决方案


当前实现将保存传递给操作的任何内容

const initState = {
  expenses:[
    { key: '1', sum: '100.67'},
    { key: '2', sum: '200.00'},
  ],
  categories: [
    { id:'1', name: 'a' },
    { id:'2', name: 'b' },
  ],
  limit: {lim:'1000'}  //<- this value I need to update
}

const rootReducer = (state = initState, action) => {
  switch(action.type){
    //some cases
    case 'UPDATE_LIMIT': {
      return {
        ...state,
        limit: action.lim // <-- this will create state.limit = <value>
      }
    }
    default:
      return state;
  }
}

因此,例如,如果您不小心做this.props.updateLimit(this.state.myLimit);了而不是this.props.updateLimit({ lim: this.state.myLimit });,则 redux 状态形状将关闭。

您可能需要调整操作以简单地采用新限制并在减速器内部处理状态形状。

注意:updateLimit动作创建者已经接受了一个值。

const rootReducer = (state = initState, action) => {
  switch(action.type){
    //some cases
    case 'UPDATE_LIMIT': {
      return {
        ...state,
        limit: {
          lim: action.lim, // <-- create the sub-key `lim`
        },
      }
    }
    default:
      return state;
  }
}

现在您可以简单地发送updateLimit您想要的新限制,即this.props.updateLimit(this.state.myLimit);.


推荐阅读