我想将函数绑定到自身内部,以便可以使用setState更改状态,帮助我解决此function(response){ this.function=this.function.bind(this) console.log(response) }
try this hopefully will work for you
axios.post(" http://${REACT_APP_SERVER_URL}/facebook", { uid: user }).then((response) => {
console.log('hello')
if (response.data.success) {
const { checked } = this.state;
const newChecked = [...checked];
newChecked.push(1)
this.setState({ checked: newChecked });
console.log(this.state.checked)
history.push("/dashboard");
}
}).catch(err=>{
console.log(err)
})
Binding a function within itself is a confusing thing to do; you're modifying the function and it probably won't do what you expect the next time it's called. Your question is a classic example of the XY problem .
What you are probably looking for is described in the React docs at https://reactjs.org/docs/faq-functions.html#how-do-i-bind-a-function-to-a-component-instance .
You have two options, call bind
, or use an arrow function
:
class MyComponent extends Component {
constructor() {
/* Bind the value of this */
this.myFunction = this.myFunction.bind(this);
}
render() {
<div>
{/* Or use an arrow function */}
<button onClick={() => this.myFunction()}>My button</button>
</div>
}
}
Try this to bind your response function
function(response){
//this.function=this.function.bind(this)
console.log(response)
}.bind(this)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.