如何在渲染函数中调用函数?

Ded*_*pul 10 react-native

如果我尝试调用该fetchToken()函数,它只是说它不是一个函数.如果我把它放在渲染功能之外this.propsundefined,我无法调用它.

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>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

pur*_*rii 10

在构造函数中绑定它

您必须将实例绑定this到该函数.它是建议为此在构造函数中.

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>
    )
}
Run Code Online (Sandbox Code Playgroud)

}


小智 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)
}
Run Code Online (Sandbox Code Playgroud)

如果你想知道为什么你不需要它为componentDidMount或componentWillUnmount,它们似乎是因为它们是组件生命周期的一部分,它们是自动引导的,但你仍然可以将它们写成箭头函数.