我是新来的反应者,在将道具传递给子组件时遇到问题
我有2个组成部分:PhotoList
和Pagination
。在PhotoList
组件中,我传递的2个道具是currentPage
和totalPage
对于Pagination
组件。
<Pagination
totalPage={Math.floor(this.state.totalImages/30)+1}
currentPage={this.state.currentPage}
clicked={this.pageChanged}
/>
内部Pagination
组件。我有一个州,我想根据range
的值计算currentPage
属性
state = {
range: [],
startPage: 1,
maxVisibleButtons: 5
}
问题是当我在componentDidMount
中访问道具时。我收到totalPage
为1而不是正确值(在我的情况下为37),并且状态中的range
属性值错误
还有另一件事是什么想法,只要range
的值更改,就重新计算currentPage
的值?
答案 0 :(得分:0)
可能 this.state.totalImages
的值在初始渲染时不可用,因此您需要在相关 range
发生变化时重新计算 props
:
class Pagination extends React.Component {
state = {
range: [],
startPage: 1,
maxVisibleButtons: 5
}
// Compute range and save into state
computeRange() {
const {totalPage} = this.props;
const newRange = [/* Some range computation based on props*/];
this.setState({ range: newRange });
}
// Initially compute range
componentDidMount() {
computeRange();
}
// Recompute range if total changed
componentDidUpdate(prevProps, prevState) {
if(this.props.totalPage !== prevProps.totalPage) {
computeRange();
}
}
}
或者使用功能组件和React.useMemo
:
const Pagination = ({totalPage, currentPage, clicked}) => {
const [startPage, setStartPage] = React.useState(1);
const [maxVisibleButtons, setMaxVisibleButtons] = React.useState(5);
const range = React.useMemo(() =>
// Or whatever you do to compute the range
new Array(totalPage)
.fill(0)
.map((el, index) => index+1
), [totalPage]);
return (
/* The render return */
);
}