我正在使用react和graphql在分页中进行数据渲染。
在安装组件时,它将获取我需要的数据
componentDidMount() {
this.onCarRender()
}
onCarRender() {
const { users, car } = this.props
if(users) {
this.setState({
//car contains data I want to render on a screen
carArray: car
})
}
}
通过graphql查询,this.state.carArray包含有关汽车的5种不同数据,当我单击另一页时,它将获取有关汽车的其他5种数据。
// carArray in Page 1
[
{ id: 1, driver: "Mario", carName: "Ferrari 488" },
{ id: 2, driver: "Solid Snake", carName: "Prious" },
{ id: 3, driver: "Link", carName: "Explorer" },
{ id: 4, driver: "Zelda", carName: "Genesis" },
{ id: 5, driver: "Ryu", carName: "Range Rover" }
]
// carArray in Page 2
[
{ id: 6, driver: "Chun-Li", carName: "Lamborghini" },
{ id: 7, driver: "Blanca", carName: "Camry" },
{ id: 8, driver: "Yasuo", carName: "Benz E-Class" },
{ id: 9, driver: "Garen", carName: "Ferrari 911" },
{ id: 10, driver: "Teemo", carName: "M1 Abrams" }
]
但这是问题所在:
当我单击第二页按钮时,除非刷新浏览器,否则this.props.car不会获取我需要的数据。
这是因为我在React.js中使用了错误的生命周期方法吗?
答案 0 :(得分:0)
我使用componentDidUpdate生命周期方法解决了它
componentDidUpdate(prevProps, prevState) {
if (prevProps.car !== this.props.car) {
this.onCarRender()
}
}