React Native Reducer数据未发送到我的页面

时间:2019-07-02 17:29:12

标签: react-native reducers

我有一个要发送到reducer的动作数据,但不是我的页面构造函数。

操作方法:

export const getTenantByID = ({ tenantID }) => {
  return (dispatch) => {
    const getTenant = {
      FirstName: 'Jonh', LastName: 'Doe', Email: 'jonh@test.com', Phone: 'xxx-xxx-xxxx',
      Unit: '101', MiddleName: '',
    };
    dispatch({
      type: GET_TENANT_DATA,
      payload: getTenant
    });
  };
};

然后,在我的减速器中

const INITIAL_STATE = {
  error: false,
  data: [],
  tenantData: {},
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case GET_TENANTS_DATA:
      return { ...state, error: false, data: action.payload };
    case GET_TENANT_DATA:
        return { ...state, error: false, tenantData: action.payload };
    default:
      return state;
  }
};

如果在案例GET_TENANT_DATA之后执行console.log(action),我可以看到有效负载的数据,因此它在减速器中正常工作。

我的页面:

constructor(props) {
    super(props);
    const { navigation } = this.props;
    const tenantID = navigation.getParam('tenantID', '0');
    this.props.getTenantByID(tenantID);
      console.log(this.props); // this show tenantData as a empty object
    this.state = {
      tenantData: this.props.tenantData
    };
  } 
  ...

const mapStateToProps = ({ tenants }) => {
  const { error, tenantData } = tenants;

  return { error, tenantData };
};

export default connect(mapStateToProps, {
  getTenantByID
})(TenantDetails);

1 个答案:

答案 0 :(得分:1)

似乎您正在使用thunk并且它是异步的,因此您需要进行await操作,以便在触发操作后可以获取更新的状态。否则,您可以删除不必要的文件。您可能还想在componentDidMount中而不是在构造函数中触发动作

componentDidMount() {
   this.getTenant();
}

getTenant = async () => {
    const { navigation } = this.props;
    const tenantID = navigation.getParam('tenantID', '0');
    await this.props.getTenantByID(tenantID); // Wait for action to complete
    console.log(this.props); // Get updated props here
    this.state = {
      tenantData: this.props.tenantData
    };
}

const mapStateToProps = ({ tenants }) => {
  const { error, tenantData } = tenants;

  return { error, tenantData };
};

export default connect(mapStateToProps, {
  getTenantByID
})(TenantDetails);

或者您可以通过componentDidUpdate

捕获更新
componentDidMount() {
   this.getTenant();
}

componentDidUpdate(previousProps) {
    if (this.props.tenantData !== previousProps.tenantData) {
       console.log(this.props); // Get updated props here
       this.state = {
          tenantData: this.props.tenantData
       };
    }
}

getTenant = async () => {
    const { navigation } = this.props;
    const tenantID = navigation.getParam('tenantID', '0');
    this.props.getTenantByID(tenantID);
}

const mapStateToProps = ({ tenants }) => {
  const { error, tenantData } = tenants;

  return { error, tenantData };
};

export default connect(mapStateToProps, {
  getTenantByID
})(TenantDetails);