Reactjs 反应+;redux:加载连接的组件时调用调度

Reactjs 反应+;redux:加载连接的组件时调用调度,reactjs,redux,react-router,react-redux,redux-thunk,Reactjs,Redux,React Router,React Redux,Redux Thunk,我是新来的。我有一个react+react router+redux应用程序,我想从子组件发出调度呼叫。现在,调度正在应用程序最顶端的my index.js文件中进行,它通过redux thunk操作和api调用从数据库加载所有数据: const store = configureStore(); store.dispatch(loadCourses()); <-- redux thunk function calling api store.dispatch(loadAuthors())

我是新来的。我有一个react+react router+redux应用程序,我想从子组件发出调度呼叫。现在,调度正在应用程序最顶端的my index.js文件中进行,它通过redux thunk操作和api调用从数据库加载所有数据:

const store = configureStore();
store.dispatch(loadCourses()); <-- redux thunk function calling api
store.dispatch(loadAuthors());

ReactDOM.render(
    <Provider store={store}>
       <Router history={browserHistory} routes={routes} />
    </Provider>,
    document.getElementById('app')
);
const store=configureStore();

store.dispatch(loadCourses()) 您可能希望在组件的
componentDidMount()
lifecycle方法中调用它。从文档中:

componentDidMount()在装入组件后立即调用。需要DOM节点的初始化应该在这里进行。如果需要从远程端点加载数据,这是实例化网络请求的好地方。在此方法中设置状态将触发重新渲染


如果您将组件中的操作作为道具,并在需要时直接调用它们:

class CoursePage extends React.Component {
  constructor(props) {
    // ...
    this.handleClick = this.handleClick.bind(this) // available to click in component with proper scope set
  }

  componentWillMount() {
    // called before component inits (only once)
    // this would be your first load, rather than calling it right
    // after you create your store
    this.props.loadCourses()
  }

  handleClick() {
    // click handler
    this.props.loadCourses();
  }

  // ...

  render() {
    // ... the rest of your component
     <button onClick={handleClick}>Refresh data</button>
    // ... the rest of your component

}
class CoursePage扩展了React.Component{
建造师(道具){
// ...
this.handleClick=this.handleClick.bind(this)//可在设置了适当范围的组件中单击
}
组件willmount(){
//在组件初始化之前调用(仅一次)
//这将是您的第一次加载,而不是正确地调用它
//创建店铺之后
this.props.loadCourses()
}
handleClick(){
//单击处理程序
this.props.loadCourses();
}
// ...
render(){
//…组件的其余部分
刷新数据
//…组件的其余部分
}

您希望避免使用
componentWillMount()
生命周期方法来进行API调用、设置事件侦听器等。我使用componentDidMount和上面的示例代码组合了您的两个答案。这解决了我的一个问题(在应用程序初始化时不加载所有内容)但它并没有解决我希望它能解决的另一个问题(也没有提到)。我为每个课程都有一个嵌套组件(author),在保存课程并重定向到课程列表视图后,它会给我一个author对象的空值错误(在列表中显示名字和姓氏).那可能是另一篇文章…看起来你走对了方向。如果你还没有,我会继续阅读。理想情况下,你不会在演示组件中提取任何数据。
class CoursePage extends React.Component {
  constructor(props) {
    // ...
    this.handleClick = this.handleClick.bind(this) // available to click in component with proper scope set
  }

  componentWillMount() {
    // called before component inits (only once)
    // this would be your first load, rather than calling it right
    // after you create your store
    this.props.loadCourses()
  }

  handleClick() {
    // click handler
    this.props.loadCourses();
  }

  // ...

  render() {
    // ... the rest of your component
     <button onClick={handleClick}>Refresh data</button>
    // ... the rest of your component

}