我对promises的es6箭头函数有疑问(在我的例子中反应)。在我的示例代码中,我只想调用一个函数洞察另一个函数。它只适用于我使用es6。我一直在网上阅读,但我并不完全理解为什么它只适用于es6。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
}
this.handleInput = this.handleInput.bind(this);
this.testing = this.testing.bind(this);
}
testing(){
console.log("hello")
}
handleInput(){
...
.then(function(){
this.test() //doesnt work
test() //doesnt work
})
.then => res{
// I actually don't require parameters, but it's
// never working unless I use this syntax
.this.test() // WORKS
}
}
render() {
return (
<div>
Hello {this.props.name}
</div>
);
}
}
答案 0 :(得分:2)
因为您正在丢失本机函数的上下文。
让我解释一下。如果你调用func就像&#39; this.test()&#39; for&#39;功能测试()&#39;您可以从当前调用上下文中调用它。所以&#39;这个&#39;关键字将包含函数调用者的上下文环境。 对于反面,箭头函数始终将上下文与创建它们的对象或函数匹配。
答案 1 :(得分:0)
关于背景的一切。当你使用非箭头函数时,上下文集是新的,而不是从外部函数继承的。如果您使用箭头功能,它将按预期工作。上下文将是外部的。 请参阅此示例,箭头函数如何保持上下文
const PollOption = ({options,selected, onChange, myTest}) => {
console.log("addafafdj", myTest)
return (
<div className="pollOption">
{options.map((choice, index) => (
<label key={index}>
<input type="radio"
name="vote"
key={index}
onChange={(e)=>onChange(e,index)}/>
{choice.tag}
</label>
))}
</div>
);
};
const VoteCount = ({totalVotes, options}) =>{
return(
<div className="VoteCount">
<h2>Total Votes {totalVotes}</h2>
<ul>
{options.map((element,index)=>(
<li>{element.tag}: {element.count}</li>
))}
</ul>
</div>
);
}
class OpinionPoll extends React.Component{
constructor(props) {
super(props);
this.state = {
selectedOption: 0,
totalVotes: 0,
choiceOneVotes: 0,
choiceTwoVotes: 0,
options: [
{tag:"A", count:0},
{tag:"B", count:0},
{tag:"C", count:0},
{tag:"D", count:0}
]
}
}
handleClick(){
console.log('submitted option', this.state.selectedOption);
this.setState(prevState => {
return {totalVotes: prevState.totalVotes + 1}
})
const selectedIndex = this.state.selectedOption
const newOption = [...this.state.options]
debugger
newOption[selectedIndex].count += 1
this.setState({
options: newOption,
})
}
test(value) {
console.log("promise worked", value)
}
handleOnChange(e,index){
console.log('selected option', index);
this.setState({
selectedOption: index
});
const newPromise = new Promise((resolve,reject)=> {
setTimeout(()=> {
resolve("11232")
},1000)
})
newPromise.then((value)=> {
this.test(value)
})
console.log("state in handlechange",this.state)
}
render(){
const myTest = "hola boy"
return (
<div className="poll">
{this.props.model.question}
<PollOption
myTest
options={this.state.options}
onChange={(e,index) => this.handleOnChange(e,index)}
selected={this.state.selectedOption}/>
<button onClick={() => this.handleClick()}>Vote!</button>
<VoteCount
totalVotes={this.state.totalVotes}
options={this.state.options}
/>
</div>
);
}
}
var json = {
question: 'Do you support cookies in cakes?',
choices:
[
{text: "Yes", value: "yes"},
{text: "No", value: "no"}
]
}
const root = document.getElementById("root");
ReactDOM.render(<OpinionPoll model ={json} />, root)
//ReactDOM.render(<div>test </div>, root)