如果我尝试调用fetchToken()
函数,它只是说它不是函数。如果我把它放在渲染函数之外this.props
是undefined
而我无法调用它。
class LoginPage extends Component {
componentDidMount() {
Linking.addEventListener('url', this.handleOpenURL);
}
componentWillUnmount() {
Linking.removeEventListener('url', this.handleOpenURL);
}
handleOpenURL(event) {
let code = event.slice(22,86);
console.log(code);
this.fetchToken(code)
}
render() {
function fetchToken(code) {
this.props.actions.fetchToken(code)
}
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<TouchableHighlight style={{backgroundColor: '#9b59b6', height: 70, padding: 20}} onPress={this.openAuth.bind(this)}>
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{color: 'white', fontSize: 16}}>Authenticate with Dribbble</Text>
</View>
</TouchableHighlight>
</View>
)
}
}
答案 0 :(得分:10)
您必须将实例this
绑定到该函数。在构造函数中执行此操作是recommend。
class LoginPage extends Component {
constructor(props) {
super(props);
this.handleOpenURL = this.handleOpenURL.bind(this);
}
componentDidMount() {
Linking.addEventListener('url', this.handleOpenURL);
}
componentWillUnmount() {
Linking.removeEventListener('url', this.handleOpenURL);
}
handleOpenURL(event) {
let code = event.slice(22,86);
console.log(code);
this.props.actions.fetchToken(code);
}
render() {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<TouchableHighlight style={{backgroundColor: '#9b59b6', height: 70, padding: 20}} onPress={this.openAuth.bind(this)}>
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<Text style={{color: 'white', fontSize: 16}}>Authenticate with Dribbble</Text>
</View>
</TouchableHighlight>
</View>
)
}
}
答案 1 :(得分:5)
有一个更清晰的解决方案:使用ES6箭头功能:
handleOpenURL = (event) => {
let code = event.slice(22,86);
console.log(code);
this.props.actions.fetchToken(code);
}
fetchToken = (code) => {
this.props.actions.fetchToken(code)
}
如果你想知道为什么你不需要它为componentDidMount或componentWillUnmount,似乎因为它们是组件生命周期的一部分,它们是自动引导的,但你仍然可以将它们写成箭头函数。