gpt4 book ai didi

reactjs - 用构造函数替换 componentWillMount() 不起作用

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

一个类用于拦截 axios 错误。为了绑定(bind)箭头函数,正在使用 componentDidMount()。现在我需要从服务器初始化数据,所以我必须使用 componentWillMount() 除非它会在 React 17 中被删除并且警告消息建议我使用构造函数。当我这样做时,它给了我一个错误。

import React, {Component} from "react";

import Modal from "../../components/UI/Modal/Modal";
import Aux from "../Auxiliary/Auxiliary";

const withErrorHandler = (WrappedComponent, axios) => {
return class extends Component{
state = {
error: null
};

// componentWillMount() {
// axios.interceptors.request.use(request => {
// this.setState({
// error: null
// });
// return request;
// });
// axios.interceptors.response.use(res => res, (error) => {
// this.setState({
// error: error
// })
// });
// }

constructor(props) {
super(props);
axios.interceptors.request.use(request => {
this.setState({
error: null
});
return request;
});
axios.interceptors.response.use(res => res, (error) => {
this.setState({
error: error
})
});
}



errorConfirmedHandler = () => {
this.setState({error: null})
};

render() {
return (
<Aux>
<Modal show={this.state.error} modalClosed = {this.errorConfirmedHandler}>
{this.state.error ? this.state.error.message : null}
</Modal>
<WrappedComponent {...this.props}></WrappedComponent>
</Aux>
);
}
}
};

export default withErrorHandler;

我从 URL 中删除了 .json 以产生错误
class BurgerBuilder extends Component {
state = {
ingredients: null,
totalPrice: 4,
purchasable: false,
purchasing: false,
loading: false,
// axiosError: null
};

componentDidMount() {
axios.get('https://burger-m.firebaseio.com/ingredients').then(response => {
this.setState({ingredients: response.data});
}).catch(error => {});
}
..
export default withErrorHandler(BurgerBuilder, axios);

&
Error Message: "index.js:1 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 _temp component."

然而,componentWillMount() 确实有效。所以我应该改变什么?

最佳答案

通过添加状态来保持构造函数简单,不要在构造函数中使用 axios 拦截器,而是在返回 JSX 代码之前在渲染中使用它。

render() {
axios.interceptors.request.use(req => {
this.setState({ error: null })
return req;
})

axios.interceptors.response.use(response => response, error => {
this.setState({ error: error })
})
return (
<Aux>
<Modal show={this.state.error} modalClosed={this.errorConfirmedHandler }>{this.state.error ? this.state.error.message : null}</Modal>
<WrappedComponent />
</Aux>
)

关于reactjs - 用构造函数替换 componentWillMount() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61755424/

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