gpt4 book ai didi

reactjs - 如何替换 componentWillRecieveProps

转载 作者:行者123 更新时间:2023-12-03 14:03:14 27 4
gpt4 key购买 nike

我是 redux 新手,关注 this tutorial使用 React 和 Redux 创建一个简单的博客应用程序。我已经完成了它,但是我注意到 componentWillRecievePropsbeing deprecated 。我试图用更新的代码替换它,但无法理解如何做到这一点。我读过this article关于用“getDerivedStateFromProps”替换“componentWillReceiveProps”,但我认为这不是 getDerivedStateFromProps 的正确用法,如 React's blog post关于用另一种替换其中一种的描述。

我当前的componentWillRecieveProps代码:

import axios from "axios";
import React from "react";
import { connect } from "react-redux";

class Form extends React.Component {
constructor(props) {
super(props);

this.state = {
title: "",
body: "",
author: ""
};

this.handleChangeField = this.handleChangeField.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}

//This is deprecated
componentWillReceiveProps(nextProps) {
console.log(this);
if (nextProps.articleToEdit) {
this.setState({
title: nextProps.articleToEdit.title,
body: nextProps.articleToEdit.body,
author: nextProps.articleToEdit.author
});
}
}


handleSubmit() {
const { onSubmit, articleToEdit, onEdit } = this.props;
const { title, body, author } = this.state;

if (!articleToEdit) {
return axios
.post("http://localhost:8000/api/articles", {
title,
body,
author
})
.then(res => onSubmit(res.data))
.then(() => this.setState({ title: "", body: "", author: "" }));
} else {
return axios
.patch(
`http://localhost:8000/api/articles/${articleToEdit._id}`,
{
title,
body,
author
}
)
.then(res => onEdit(res.data))
.then(() => this.setState({ title: "", body: "", author: "" }));
}
}

handleChangeField(key, event) {
this.setState({
[key]: event.target.value
});
}

render() {
const { articleToEdit } = this.props;
const { title, body, author } = this.state;

return (
<div className="col-12 col-lg-6 offset-lg-3">
<input
onChange={ev => this.handleChangeField("title", ev)}
value={title}
className="form-control my-3"
placeholder="Article Title"
/>
<textarea
onChange={ev => this.handleChangeField("body", ev)}
className="form-control my-3"
placeholder="Article Body"
value={body}
/>
<input
onChange={ev => this.handleChangeField("author", ev)}
value={author}
className="form-control my-3"
placeholder="Article Author"
/>
<button
onClick={this.handleSubmit}
className="btn btn-primary float-right"
>
{articleToEdit ? "Update" : "Submit"}
</button>
</div>
);
}
}

const mapDispatchToProps = dispatch => ({
onSubmit: data => dispatch({ type: "SUBMIT_ARTICLE", data }),
onEdit: data => dispatch({ type: "EDIT_ARTICLE", data })
});

const mapStateToProps = state => ({
articleToEdit: state.home.articleToEdit
});

export default connect(
mapStateToProps,
mapDispatchToProps
)(Form);

Full Repo Codesandbox

如果 componentWillRecieveProps 被弃用,我应该如何更新我的代码?

编辑:使用getDerivedStateFromProps,nextProps仍然具有以前的值,因此当返回对象时,状态被设置回以前的状态,实际上没有进行更新。

尝试使用 prevState 值在这种情况下不起作用,因为初始 prevState 值都是空字符串,在组件呈现时(在初始页面加载时以及单击编辑按钮时发生),这些值都会被调用并置于状态中。

    static getDerivedStateFromProps(nextProps, prevState) {
if (
JSON.stringify(nextProps.articleToEdit) !==
JSON.stringify(prevState.articleToEdit)
) {
console.log(nextProps);
console.log(prevState);
return {
title: nextProps.articleToEdit.title,
body: nextProps.articleToEdit.body,
author: nextProps.articleToEdit.author
}; // <- is this actually equivalent to this.setState()?
} else {
return null;
}
}

最佳答案

通过引入名为 getDerivedStateFromProps() 的新生命周期方法,已弃用 componentWillReceiveProps() 方法。

请记住,您应该始终将当前 Prop 与以前的 Prop 进行比较,如下所示,如果它们不相同,则执行 setState 否则您将陷入无限 setState 警告

替换以下代码代替 componentWillReceiveProps 方法

   static getDerivedStateFromProps(nextProps,  prevState)  {
//Below I used JSON.stringify to compare current props with previous props of articleToEdit object
if (JSON.stringify(nextProps.articleToEdit) !== JSON.stringify(prevState.artileToEdit)){
return({
title: nextProps.articleToEdit.title,
body: nextProps.articleToEdit.body,
author: nextProps.articleToEdit.author
});// <- this is setState equivalent
}
return null;
}

编辑:

您无法在 getDerivedStateFromProps 函数内访问 this.props。如果您想访问函数内的一些先前的 props(例如用于比较),那么您可以在状态内镜像这些值。然后你可以将 nextProps 与上面存储在 state 中的值进行比较

检查此线程以更好地理解

https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#updating-state-based-on-props

关于reactjs - 如何替换 componentWillRecieveProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52885661/

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