gpt4 book ai didi

reactjs - react +还原: call dispatch when connected component loads

转载 作者:行者123 更新时间:2023-12-03 14:14:08 25 4
gpt4 key购买 nike

我是新来的 react 。我有一个 React + React Router + Redux 应用程序,我想从子组件进行调度调用。现在,调度发生在应用程序最顶部的 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')
);

如果我想在下面的(连接的)子组件加载时加载数据或能够刷新数据怎么办?

import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as courseActions from '../../actions/courseActions';
import CourseList from './CourseList';
import {browserHistory} from 'react-router';


class CoursesPage extends React.Component {
constructor(props, context) {
super(props, context);
this.redirectToAddCoursePage = this.redirectToAddCoursePage.bind(this);
}

redirectToAddCoursePage() {
browserHistory.push('/ReactJS/course');
}

render() {
const {courses} = this.props;
return (
<div>
<div className="page-header">
<h3>Courses</h3>
</div>
<input type="submit" value="New Course" className="btn btn-default btn-toolbar pull-right" onClick={this.redirectToAddCoursePage} />
<div className="panel panel-default ">
<div className="panel-heading">
<span>&nbsp;</span>
</div>
<CourseList courses={courses} />
</div>
</div>
);
}
}

CoursesPage.propTypes = {
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired
};

function mapStateToProps(state, ownProps) {
return {
courses: state.courses
};
}

function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(courseActions, dispatch),
};
}

export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);

在我看来,当前的设置方式(来 self 遵循的教程)在应用程序启动时加载整个数据库中的所有数据效率很低,特别是如果多个数据中可能有数千行数据的话表。

因此,如果我想在加载时从该组件调用 store.dispatch(loadCourses()) ,它会去哪里?

最佳答案

您可能希望在组件的 componentDidMount() 生命周期方法中调用此方法。来自文档:

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

https://facebook.github.io/react/docs/react-component.html#componentdidmount

关于reactjs - react +还原: call dispatch when connected component loads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43682325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com