gpt4 book ai didi

javascript - React JS - 无法在尚未安装的组件上调用 setState

转载 作者:行者123 更新时间:2023-12-03 23:38:56 25 4
gpt4 key购买 nike

我在 React JS 中有我的应用程序。我正在从 http://localhost:8080/api/list 的 API 获取数据:
以下是我从 Google Chrome 控制台中的 REST API 获得的数据:

0:{
id: 4
supplierFirstname: "Tom"
supplierLastName: "ABC"
supplierTitle: "TomTheSupplier"
accountNumber: 1122234444
address: "111 ADrive, 1234 ST."
companyName: "TheTom Company & Associates"
email: "tomtomjayjay@email.com"
hourlyRate: 29
phoneNumber: 123456789
otherPhoneNumber: 1023456789
paymentTerms: "Credit"
notes: "Some Supplier"
createdAt: null
typeOfGoods: "Supplies"
website: "www.abc_123.com"
products: [{…}]
components:
[
0: {id: 5, name: "AComponent", unit: null, quantity: 0, componentCost: 0, …}
]

}
这是我的 react 代码:
class SupplierData extends React.Component {
constructor(props) {
super(props);
this.state = {
supplier: [
{
id: 0,
supplierTitle: "Supplier Title",
supplierFirstName: "First Name",
supplierLastName: "Last Name",
companyName: "Company Name",
phoneNumber: "Phone Number",
otherPhoneNumber: "Phone Number (Other)",
accountNumber: "Account Number",
email: "Email",
address: "Address",
website: "Website",
hourlyRate: "Hourly Rate",
typeOfGoods: "Type Of Goods",
paymentTerms: "Payment Terms",
createdAt: "Created At",
notes: "Notes",
products: "Products",
components: "Components",
},
],
errorMessage: [],
};
this.ListAllSuppliers = this.ListAllSuppliers.bind(this);
}

ListAllSuppliers = async () => {
return await axios
.get(`http://localhost:8080/api/suppliers/supplier/list`)
.then((response) => {
let apiResults = response.data;
console.log(apiResults);
this.setState({ supplier: apiResults }); <--- The error happens here.
})
.catch((error) => {
this.setState({ errorMessage: this.state.errorMessage.push(error) });
});
};

componentDidMount() {
this.ListAllSuppliers();
}
}

export default SupplierData;
我面临的问题是 react 状态。我收到以下错误:
Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might 
indicate a bug in your application. Instead, assign to `this.state` directly or define a `state =
{};` class property with the desired state in the SupplierData component.
问题:
我想设置状态。
有什么可能解决上述错误?

最佳答案

尽管您正在混合对 .then 的调用,但代码本身大部分都很好。和 .catchasync/await这不是最佳实践,您正在使用 bind不必要的箭头函数。
在您启动 axios 之后,听起来您的组件正在卸载。在它返回之前调用和调用,这将导致您调用 setState在未安装的组件上。 (虽然错误的措辞与我看到的略有不同。)
为避免这种情况,您可以 cancel来自 componentWillUnmount 的 axios 调用通过传递 cancelToken在选项中,并使用 cancelsource上的方法来自 componentWillUnmount . (内置的 fetch 通过 AbortController 提供相同的功能。)(如果您正在执行不支持取消的操作,作为后备,您可以在 this.unmounted 中设置 componentWillUnmount,然后检查它并如果你看到 setState 是真的,不要调用 this.unmounted。)
代码还有一些其他问题;这是带有上述取消 token 和内联解决的其他问题的更新版本(请参阅评论):

class SupplierData extends React.Component{
constructor(props){
super(props);
this.state = {
supplier: [
{
id: 0,
supplierTitle: "Supplier Title",
supplierFirstName: "First Name",
supplierLastName: "Last Name",
companyName: "Company Name",
phoneNumber: "Phone Number",
otherPhoneNumber: "Phone Number (Other)",
accountNumber: "Account Number",
email: "Email",
address: "Address",
website: "Website",
hourlyRate: "Hourly Rate",
typeOfGoods: "Type Of Goods",
paymentTerms: "Payment Terms",
createdAt: "Created At",
notes: "Notes",
products: "Products",
components: "Components"
},
],
errorMessage: [],
};
// No need to bind `listAllSuppliers`, you don't use it as a callback

// A single cancel source that can cancel multiple operations
this.cancelSource = axios.CancelToken.source();
}

// Use an async method
// Note the initial lower case `l` (not `L`), which is standard in JavaScript
async listAllSuppliers() {
// In an `async` function, you use `try`/`catch` and `await`, not
// `.then` / `.catch` methods
try {
const response = await axios.get(
`http://localhost:8080/api/suppliers/supplier/list`,
{cancelToken: this.cancelSource.token}
);
const supplier = response.data;
console.log(supplier)
this.setState({supplier});
} catch (error) {
// Updating state based on existing state requires the callback form
// of `setState` , and you must never directly modify state objects
this.setState(({errorMessage}) => ({
errorMessage: [...errorMessage, error]
}));
}
}

componentDidMount() {
this.listAllSuppliers();
}

componentWillUnmount() {
// Cancel any outstanding axios calls
this.cancelSource.cancel("Component unmounted");
}

// Presumably you do have a `render` method, you'd get a different React error if you didn't
render() {
// ...
}
}

export default SupplierData;

关于javascript - React JS - 无法在尚未安装的组件上调用 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67214162/

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