【问题标题】:Unable to call Curried function from componentDidMount() in React component无法从 React 组件中的 componentDidMount() 调用 Curried 函数
【发布时间】:2017-08-15 14:55:39
【问题描述】:

我的操作中有以下功能

export const fetchDeviceData = (deviceData: Object): ThunkAction => (dispatch: Dispatch, getState: GetState, axios: any) => {

    console.log('inside fetchDeviceData', deviceData);
    return dispatch(fetchDeviceDataAPI(axios, url, deviceData));

};

我在组件的 componentDidMount() 块中按以下方式调用它

// type declaration (imported from a separate file)
export type DeviceReg = {
    [deviceData: Object]: {
        readyStatus: string,
        err: any,
        payload: Object,
    }
};

// Prop type declaration
type Props = {
    device_reg: DeviceRegType,
    fetchDeviceData: () => void,
}

componentDidMount() {
    const x = this.getDeviceData();
    console.log('header mount mobile', x);
    action.fetchDeviceData(x);
}

// The connector
const connector: Connector<{}, Props> = connect(
    ({ device_reg }: Reducer) => ({ device_reg }),
    (dispatch: Dispatch) => ({
        fetchDeviceData: (deviceData) => dispatch(action.fetchDeviceData(deviceData)),
    }),
);
export default Header;

问题是,当我在函数中包含参数dispatch: Dispatch, getState: GetState, axios: any 时,不会调用 fetchDeviceData(x) 函数,但它可以在其他方面工作。导入和依赖不是问题,因为我已经验证了很多次。

任何建议、提示或解决方案都会有很大帮助。如果您需要任何关于我的问题的说明或上下文,请告诉我。

提前致谢。

【问题讨论】:

  • 你能分享一下你的connect你的组件吗?
  • 在编辑中包含了一些额外的细节。请看一看。
  • 看起来你应该调用 this.props.fetchDeviceData(...)
  • 不工作,给我一个 TypeError: this.props.fetchDeviceData is not a function。如果我从道具调用它,我需要在任何地方传递这个函数吗?对不起,仍然是新的反应。实际上这是 Header 组件的一部分,只需要调用一次,所以我没有为它制作路由。当我记录 this.props 时,它给了我一个空对象。

标签: reactjs react-redux redux-thunk


【解决方案1】:

您可以尝试从 dispatch: Dispatch, getState: GetState, axios: any 中删除 axios: any 吗?

我认为应该只有 dispatch 和 getState,因为这是由 redux-thunk 注入的。

【讨论】:

  • 已经试过了,没用。控件进入函数内部的唯一情况是我删除了所有三个参数(dispatch、getState 和 axios)。不知道为什么。
【解决方案2】:

尝试更改您的连接代码以使用对象形式:

connect(
    <yourMapStateToProps>,
    {
        fetchDeviceData: actions.fetchDeviceData,
    }     
)

这应该使fetchDeviceData 可用作您调用的道具。

另外,尝试从函数签名中删除 axios 参数,只留下 dispatchgetState

【讨论】:

  • 好的,会试试的。但是你能告诉我为什么这种方法不起作用吗?在组件中直接调用函数是不是不对?
  • 不,操作应该是dispatched(除非它们通过connect 绑定,如上所述)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
  • 2020-02-15
  • 2018-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多