【问题标题】:How to pass value from tcomb-form-native to reducer? React + redux如何将值从 tcomb-form-native 传递给 reducer?反应 + 还原
【发布时间】:2018-03-13 15:03:55
【问题描述】:

在我的项目中,我使用tcomb-form-native 库来验证表单。 Redux 工作正常,但我无法将输入值传递给减速器。我必须这样做,因为我想用字段中的数据创建数组。

如何将输入值传递给 reducer? 或者也许这个库不可能,我必须使用另一个库?

Form.js

const mapDispatchToProps = dispatch => {
  return {
      closeExpenseDialog: (value) => dispatch({type: 'CLOSE_EXPENSE_DIALOG'}),
  };
};

const mapStateToProps = state => {
  return {
      value: state.closeExpenseDialog.value,
  };
};


const Form = t.form.Form;

const Expense = t.struct({
  expense: t.String,
  cost: t.Number
});

const options = {
  fields: {
    expense: {
      error: 'This field is required'
    },
    cost: {
      error: 'This field is required'
    }
  }
};

handleClick = () => {
    const value = this._form.getValue();
    if (value) {
      console.log(value);
      this.props.closeExpenseDialog(value);
    } else {
      console.log('validation failed');
    }
  }

  <Form 
   type={Expense}
   ref={c => this.props._form = c}
   options={options} 
   value={this.props.value}
  />
  <ActionButton
   onPress={this.props.closeExpenseDialog}
   title={title}
  />

Reducer.js

const initialState = {
    value: {}
};
const mainReducer = (state = initialState, action) => {
 switch (action.type) { 
   case 'CLOSE_EXPENSE_DIALOG':
     console.log('it works')
     console.log(state.value) //undefined
   default:
     return state;
   }
  };

【问题讨论】:

    标签: javascript validation react-native redux tcomb-form-native


    【解决方案1】:

    我需要添加onChange() 属性并使用它将对象value 传递给Reducer。

    Form.js

    const Expense = t.struct({
      expense: t.String,
      cost: t.Number
    });
    
    const options = {
       fields: {
        expense: {
          error: 'This field is required'
        },
        cost: {
          error: 'This field is required'
       }
     }
    };
    
    handleClick = () => {
       const value = this._form.getValue();
        if (value) {
      this.props.submitExpenseDialog();
     } 
    }
    
    <Form 
     type={Expense}
     ref={c => this._form = c}
     options={options} 
     value={this.props.value}
     onChange={this.props.changeExpenseInputs}
    />
    <ActionButton
     onPress={this.handleClick}
     title={title}
    />
    

    Reducer.js

    const initialState = {
        value: {}
    };
    const mainReducer = (state = initialState, action) => {
     switch (action.type) { 
       case 'SUBMIT_EXPENSE_DIALOG':
         console.log(state.value)
       default:
         return state;
     }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      相关资源
      最近更新 更多