首页 > 解决方案 > 如何从状态中获取 reduxFrom 的初始值?

问题描述

我正在使用我的表单和 react redux。我有相同的表格来编辑和创建一个新表格。

我希望,在打开我的表单时,如果进行编辑,我会从我的 api 中输入表单的初始值。

我已经尝试过官方文档,但它不起作用。

这是我的表格:

class Form extends Component {

  componentDidMount () {
    const tripId = this.props.match.params.uid;
    if(tripId){
      this.fetchData(tripId);
    }
  }

  fetchData = async (tripId) => {
    axios.defaults.headers.common['Authorization'] = 'token';
    axios.defaults.headers.common['Accept'] = 'application/vnd.trips.v1+json';
    await axios.get(`myurl`) 
    .then(res => {
      const trip = res.data;
      this.setState({ 
        trip: trip,
        isLoading: false,
        initialValues: trip
      });
    })
    console.log('Terminou de carregar')
  }

(....)
Form = reduxForm({ form: 'trip', enableReinitialize : true })(Form)
const mapStateToProps = state => {
  const { intl, vehicleTypes, users, dialogs, trip } = state

  return {
    intl,
    vehicleTypes,
    users,
    dialogs,
    initialValues: trip
  }
}

export default connect(
  mapStateToProps, { setDialogIsOpen }
)(injectIntl(withRouter(withTheme()(Form))))

但是我的 initialValues 永远不会被填充,并且总是空白。我调试了代码,我看到我的 API 正在加载并设置我的 fetchData 方法的状态。那么,我在这里做错了什么?

标签: reactjsreact-reduxredux-form

解决方案


首先,您尝试initialValues通过this.setState哪个不起作用,reduxForm 期望initialValuesprops.

application state需要提一下, and之间有区别component local state,第一个 -application state- 显然是由 redux 管理的,另一个 -local component state- 是由 react 管理的,你可以通过调用来修改它this.setState

所以要解决这个问题,当你从你的 api 接收数据时,你应该调度一个动作,并更新你的道具mapStateToProps

您的代码应如下所示:

class Form extends Component {

  componentDidMount () {
    const tripId = this.props.match.params.uid;
    if(tripId){
      this.fetchData(tripId);
    }
  }

  fetchData = async (tripId) => {
    await axios.get(`https://toptal-backend-fmaymone.c9users.io/trips/${tripId}`) 
    .then(res => {
      const trip = res.data;
      this.props.fillTheForm(trip);
    })
    console.log('Terminou de carregar')
  }

(....)
Form = reduxForm({ form: 'trip', enableReinitialize : true })(Form)
const mapStateToProps = state => {
  const { intl, vehicleTypes, users, dialogs, trip } = state

  return {
    intl,
    vehicleTypes,
    users,
    dialogs,
    initialValues: trip
  }
}

const fillTheForm = (dispatch) => (trip) => {
  // here you dispatch the action and update your application state
  // in your reducer when this action is dispatched,
  // then mapStateToProps should be called and the data you just
  // passed in your reducer should be in (state)
  dispatch()
}

export default connect(
  mapStateToProps, { setDialogIsOpen, fillTheForm }
)(injectIntl(withRouter(withTheme()(Form))))

推荐阅读