gpt4 book ai didi

javascript - 正在将我的类组件重构为 Functional 组件,并且在 useEffect 方面遇到了一个非常困难的问题

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

我想问题是,当我在 React 中将代码从类重构为功能组件时,是因为 useEffect 中没有很容易允许的 prevProps。我不完全知道如何解决它。
首先,像这样的 prop-type 有变量。

const propTypes = {
items: PropTypes.array.isRequired,
onChangePage: PropTypes.func.isRequired,
initialPage: PropTypes.number,
pageSize: PropTypes.number,
};
const defaultProps = {
initialPage: 1,
pageSize: 5,
};
然后在下面我写了一个可以正常工作的类组件。
class Pagination extends React.Component {
constructor(props) {
super(props);
this.state = { pager: {} };
}
componentDidMount() {
if (this.props.items && this.props.items.length) {
this.setPage(this.props.initialPage);
}
}
componentDidUpdate(prevProps) {
if (this.props.items !== prevProps.items) {
this.setPage(this.props.initialPage);
}
}
那么问题就来了。我试图将类组件更改为功能组件。
它看起来像这样。
function Pagination2(props) {
const [pager, setPager] = useState({ pager: {} });
useEffect(() => {
if (props.items && props.items.length) {
setPage(props.initialPage);
}
}, []);

const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const prevItems = usePrevious(props.items);
useEffect(() => {
if (props.items !== prevItems) {
setPage(props.initialPage);
}
console.log(prevItems); -> it shows undefined on console
}, []);
它完全不起作用,我已经被困在其中很长时间了。我该如何解决这个问题?
我愿意在这里听到任何消息。非常感谢!

最佳答案

你只能在一个 useEffect 中做到

function Pagination2(props){

function setPage(data){
//TODO
}

useEffect(() => {
if(!props.items && !props.items.length) return
setPage(props.initialPage)
}, [props.items])

return "hi"
}
useEffect只会在 props.items 时运行变化

关于javascript - 正在将我的类组件重构为 Functional 组件,并且在 useEffect 方面遇到了一个非常困难的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64425703/

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