0

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

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

表单.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}
  />

减速器.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;
   }
  };
4

1 回答 1

0

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

表单.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}
/>

减速器.js

const initialState = {
    value: {}
};
const mainReducer = (state = initialState, action) => {
 switch (action.type) { 
   case 'SUBMIT_EXPENSE_DIALOG':
     console.log(state.value)
   default:
     return state;
 }
};
于 2018-03-14T12:18:43.417 回答