我一直在努力弄清为什么render()
之后没有叫mapStateToProps()
。
当前的工作顺序是
getInitialProps
->mapStateToProps
->mapDispatchToProps
->constructor
->render
->componentDidMount(here dispatch with Redux)
->mapStateToProps
->结束
就像您看到的顺序一样,应该在调度发生后调用render(),以便使用Redux的调度数据来呈现页面。
有人知道为什么吗?
pages / search / index.js
import { connect } from "react-redux";
import Container from "./container";
import { actionCreators as storeActions } from "lib/modules/stores";
const mapStateToProps = (state, ownProps) => {
const { storeList } = state;
return { storeList };
};
const mapDispatchToProps = (dispatch, ownProps) => {
const { searchTerm } = ownProps;
return {
searchByTerm: pageNum => {
dispatch(storeActions.searchByTerm(searchTerm, pageNum));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Container);
pages / search / container.js
import Search from "./presenter";
class Index extends React.Component {
static async getInitialProps(context) {
const { searchTerm } = context.query;
return {
searchTerm
};
}
state = {
loading: true,
offset: 0,
page: 1,
limit: 10,
nlabel: ">>",
plabel: "<<"
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
const { searchByTerm } = this.props;
const { page } = this.state;
searchByTerm(page);
}
render() {
const { classes, storeList, goToSearch, searchTerm } = this.props;
return (
<Search
{...this.state}
storeList={storeList}
searchTerm={searchTerm}
/>
);
}
}
export default Index;