【问题标题】:How to use reducers in nested components?如何在嵌套组件中使用减速器?
【发布时间】:2019-08-13 19:31:41
【问题描述】:

我有一个 react.component - FetchData。它与 action-reducer-store 有联系。在 action-reducer-store 中,它从 api 获取数据并在 FetchData 组件中呈现结果。

export class FetchData extends Component {
    constructor(props) {
        super(props);
        this.props.requestWeatherForecasts(0);
    }

  render() {
    return ...;
  }
}

export default connect(
  state => state.weatherForecasts,
  dispatch => bindActionCreators(actionCreators, dispatch)
)(FetchData);

如果我使用路由直接进入组件,它工作得非常好:

<Route path='/fetch-data/' component={FetchData}>

如果我将 FetchData 移动到另一个组件,例如 Home:会出现问题:

const Home = props => (<FetchData />)

所以我用路由去组件主页:

<Route exact path='/' component={Home} />

并希望在 Home 组件中看到 FetchData,但会出现错误,例如 FetchData 中根本没有连接的 action-reducer-store

我一步一步的行动:

我创建了一个 asp.net core react.js + redux 空应用程序。 然后我将 FetchData.js 类更改为导出类。

export class FetchData extends Component

然后我在 Home.js 中导入 FetchData 并替换 body。

import React from 'react';
import { connect } from 'react-redux';
import { FetchData } from './FetchData';

const Home = props => (
    <FetchData />
);

export default connect()(Home);

在那一刻,reducer 停止在 FetchData.js 中工作(或者至少看起来是这样)

  • 我尝试将 Home.js 设为 React.Component 类。
  • 我尝试在 FetchData.js 中添加带有 super(props) 的构造函数。
  • 我已尝试将默认连接从 FetchData 添加到 Home。

【问题讨论】:

  • 你记得 mapDispatchtoProps 和 mapStatetoProps 吗?
  • 你能把整个文件的代码贴出来吗?
  • 您需要与 FetchData 连接,因此请确保它是文件底部的export default connect(mapStateToProps, mapDispatchToProps)(FetchData)
  • @Mark,我已经在 git 上发布了它-github.com/Demonell/ReduxAppFetchData.js 在按钮上有:export default connect(state => state.weatherForecasts, dispatch => bindActionCreators(actionCreators, dispatch))(获取数据); - 当它没有嵌套时它工作正常
  • export default connect()(Home); 更改为 export default Home。此处无需使用connect

标签: asp.net-core react-redux


【解决方案1】:

您的组件导入不正确

import React from 'react';
import { connect } from 'react-redux';
import FetchData from './FetchData';

const Home = props => (
    <FetchData />
);

export default connect()(Home);

删除FetchData 周围的括号,括号用于从文件中进行非默认导出。在你的情况下是./FetchData。由于您使用了export default,因此您不需要括号。

【讨论】:

    猜你喜欢
    • 2016-04-16
    • 2020-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多