在 getDerivedStateFromProps 中 API 调用后返回状态
Returning state after API call inside getDerivedStateFromProps
我有一个 React 组件,它从 parent 接收用于过滤的道具。当 parent 道具改变时,我在以下代码的 child 中使用 getDerivedStateFromProps
:
static getDerivedStateFromProps(props, state) {
if (props.filter === null) {
return state;
}
const { name, description } = props.filter;
ApiService.get("cards", { name: name, description: description })
.then(response => {
console.log("get request returned ", response.data);
return { cards: response.data };
}
);
}
在控制台中,response.data
日志是 objects 的适当数组。但是状态不会更新,渲染函数仍然使用旧的 cards
数组,而不是从 ApiService
响应中收到的数组。我如何才能使 cards
数组正确更新,以便在下一次渲染时显示过滤后的卡片?
getDerivedStateFromProps
不是正确的生命周期钩子。您需要将获取代码放在 componentDidMount
和 componentDidUpdate
中,并在数据可用后使用 this.setState
。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: null,
}
}
componentDidMount() {
this.loadData();
}
componentDidUpdate(prevProps) {
if (this.props.filter !== prevProps.filter) {
this.loadData();
}
}
loadData() {
const { name, description } = this.props.filter;
ApiService.get("cards", { name: name, description: description })
.then(response => {
this.setState({ cards: response.data });
});
)
render() {
if (!this.state.cards) {
return <div>Loading...</div>
}
return (
// some jsx using the cards
)
}
}
我有一个 React 组件,它从 parent 接收用于过滤的道具。当 parent 道具改变时,我在以下代码的 child 中使用 getDerivedStateFromProps
:
static getDerivedStateFromProps(props, state) {
if (props.filter === null) {
return state;
}
const { name, description } = props.filter;
ApiService.get("cards", { name: name, description: description })
.then(response => {
console.log("get request returned ", response.data);
return { cards: response.data };
}
);
}
在控制台中,response.data
日志是 objects 的适当数组。但是状态不会更新,渲染函数仍然使用旧的 cards
数组,而不是从 ApiService
响应中收到的数组。我如何才能使 cards
数组正确更新,以便在下一次渲染时显示过滤后的卡片?
getDerivedStateFromProps
不是正确的生命周期钩子。您需要将获取代码放在 componentDidMount
和 componentDidUpdate
中,并在数据可用后使用 this.setState
。
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
cards: null,
}
}
componentDidMount() {
this.loadData();
}
componentDidUpdate(prevProps) {
if (this.props.filter !== prevProps.filter) {
this.loadData();
}
}
loadData() {
const { name, description } = this.props.filter;
ApiService.get("cards", { name: name, description: description })
.then(response => {
this.setState({ cards: response.data });
});
)
render() {
if (!this.state.cards) {
return <div>Loading...</div>
}
return (
// some jsx using the cards
)
}
}