Reactjs 组件未接收更新的状态
我有一个Paypal按钮,应该可以从州政府那里获取要捕获的金额Reactjs 组件未接收更新的状态,reactjs,Reactjs,我有一个Paypal按钮,应该可以从州政府那里获取要捕获的金额 state = { amount: 0, }; 状态完全改变,但按钮中的金额保持不变,即金额为0 componentDidMount() { console.log(this.state.amount) let amount=this.state.amount; paypal .Buttons({ createOrder: function (da
state = {
amount: 0,
};
状态完全改变,但按钮中的金额保持不变,即金额为0
componentDidMount() {
console.log(this.state.amount)
let amount=this.state.amount;
paypal
.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: [
{
amount: {
value: amount,
},
},
],
});
},
onError: function(err){
console.log(err)
}
})
.render("#paypal");
}
}
我试着把按钮放在componentdiddupdate
中,但这只是在每次状态改变时重复呈现按钮
componentDidUpdate(){
console.log(this.state.amount)
paypal
.Buttons({
createOrder: function (data, actions) {
return actions.order.create({
purchase_units: [
{
amount: {
value: amount,
},
},
],
});
},
onError: function(err){
console.log(err)
}
})
.render("#paypal");
}
我得到Paypal按钮在安装组件时呈现,但是按钮如何从状态接收更新的值在
componentDidMount
中声明的变量数量
被限制在componentDidMount方法的范围内,并且不会随着未来状态的更改而更新
...
amount: {
value: this.state.amount
},
...
您可以在绑定createOrder函数后直接使用amount from state的引用
componentDidMount() {
console.log(this.state.amount)
paypal
.Buttons({
createOrder: (data, actions) => { // Implemented as arrow for binding
return actions.order.create({
purchase_units: [
{
amount: {
value: this.state.amount, // Will take the value from state instead of closure
},
},
],
});
},
onError: function(err){
console.log(err)
}
})
.render("#paypal");
}
}
componentDidMount
中声明的变量amount
被限制在componentDidMount方法的范围内,并且不会随着状态的未来更改而更新
您可以在绑定createOrder函数后直接使用amount from state的引用
componentDidMount() {
console.log(this.state.amount)
paypal
.Buttons({
createOrder: (data, actions) => { // Implemented as arrow for binding
return actions.order.create({
purchase_units: [
{
amount: {
value: this.state.amount, // Will take the value from state instead of closure
},
},
],
});
},
onError: function(err){
console.log(err)
}
})
.render("#paypal");
}
}
你能把组件的完整代码包括进去吗?paypal库的render函数是什么?你在mount上实例化了paypal按钮,太完美了。但是,您可能还应该在每次状态更改时更新这些PayPal函数。也许你可以在每次更新时重新定义PayPal的内容(?)研究react生命周期方法,找出如何做到这一点。ComponentWillReceive道具可能是一种方法,但我在手机上,记不清了。你能提供组件的完整代码吗?paypal库的render函数是什么?你在mount上实例化了paypal按钮,太完美了。但是,您可能还应该在每次状态更改时更新这些PayPal函数。也许你可以在每次更新时重新定义PayPal的内容(?)研究react生命周期方法,找出如何做到这一点。ComponentWillReceive-props可能是该方法,但我在手机上,记不清了。我尝试了这个方法,但客户端抛出了一个错误:“错误:无法读取未定义”的属性“金额”,请将createOrder转换为箭头函数,如图所示。这是将This
绑定到类组件时所必需的。Oh yeah没有注意到这一点(新的arrow函数)。现在它工作得很好我试过了,客户端抛出了一个错误,错误是'error:cannotreadproperty'amount'为undefined'Please convert createOrder为arrow函数,如图所示。这是将This
绑定到类组件时所必需的。Oh yeah没有注意到这一点(新的arrow函数)。现在它工作得很好