我正在使用 React v 16.3.2,并正在构建一个应用来与 Firebase 上的数据库进行订单通信,同时还使用 axios 0.18.0。
我期望一旦我点击某个按钮(继续),它就会在加载时在屏幕上创建这个旋转效果,所以我有以下代码:
purchaseContinueHandler = () => {
this.setState = ({loading: true});
const order = {
ingredients: this.state.ingredients,
price: this.state.totalPrice,
customer: {
name: 'Name',
address: {
street: 'teststreet 1',
zipCode: '86753',
country: 'U.S.'
},
email: 'example@example.com'
},
deliveryMethod: 'fastest'
}
axios.post('/orders.json', order)
.then(response => { this.setState( { loading: false } );
})
.catch(error => {
this.setState( { loading: false } ); //**<--This is where i get the error**
});
}
我运行它并在应用程序上点击“继续”并收到错误:
Unhandled Rejection (TypeError): _this.setState is not a function
它指向上面列出的行。
遇到this documentation并尝试实现对他有用的解决方案(创建一个 constructor()
并将 this
绑定(bind)到 this
),但这不起作用。
我读到这不再自动添加到函数中,但不确定如何处理这些信息,我对 React 还很陌生。
有什么建议吗?
最佳答案
您在第一行代码中分配一个对象给setState
,因此当您稍后尝试调用它时,它不再是一个函数...
this.setState = ({loading: true});
应该是
this.setState({loading: true})
关于javascript - React .setState 返回类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50497613/