调用 this.props.message() onClick

Call this.props.message() onClick

我已将 this.props.message() 传递给我的重定向组件,我希望它在单击按钮时闪烁。

但它只在 componentDidMount() 中有效,在 handleRedirection() 中无效,如下面的评论所示:

Spotify.jsx:

  componentDidMount() {
    const params = this.getHashParams();
    const access_token = params.access_token;
    const state = params.state;
    const storedState = localStorage.getItem(Credentials.stateKey);
    localStorage.setItem('spotifyAuthToken', access_token);
    localStorage.getItem('spotifyAuthToken');

    if (window.localStorage.getItem('authToken')) {
      this.setState({ isAuthenticatedWithSpotify: true });
    };
    if (access_token && (state == null || state !== storedState)) {
      alert('Click "ok" to finish authentication with Spotify');
    } else {
      localStorage.removeItem(Credentials.stateKey);
    }
    this.props.onConnectWithSpotify(access_token); 
    this.props.message('You linked your Spotify account!', 'success');//works here, but this is undesired
  };

  // NOTE1: this is where app is redirected to Spotify Server, in which the application states a redirection page, in my case, `localhost`.
  handleRedirect(event) {
    const params = this.getHashParams();
    const access_token = params.access_token;
    console.log(access_token);

    const state = this.generateRandomString(16);
    localStorage.setItem(Credentials.stateKey, state);

    let url = 'https://accounts.spotify.com/authorize';
    url += '?response_type=token';
    url += '&client_id=' + encodeURIComponent(Credentials.client_id);
    url += '&scope=' + encodeURIComponent(Credentials.scope);
    url += '&redirect_uri=' + encodeURIComponent(Credentials.redirect_uri);
    url += '&state=' + encodeURIComponent(state);
    this.props.message('You linked your Spotify account!', 'success');//does not work anywhere inside here
    window.location = url;
    //NOTE2: after button is clicked, browser shows: http://localhost/#access_token=mytoken&token_type=Bearer&expires_in=3600&state=SRVMdf2PBuSddwU8 
    // I guess the issue here might have a correlation to this
  };

  render() {
    const {menu} = this.props;
    if (menu.length === 0 ){
      return (
        <div className="button_container">
          <button className="sp_button" onClick={(event) => this.handleRedirect(event)}>
            <strong>LINK YOUR SPOTIFY ACCOUNT</strong>
          </button>
        </div>
      )
    }else{
      return (<Redirect to={'/menus'} />)}
  }

App.jsx(函数作为 props 传递):

  message(name='Sanity Check', type='success') {
    this.setState({
      messageName: name,
      messageType: type
    });
    setTimeout(() => {
      this.removeMessage();
    }, 3000);
  };
  removeMessage() {
    this.setState({
      messageName: null,
      messageType: null
    });
  };

render() {
    return (
      <div>
        <NavBar
          title={this.state.title}
          isAuthenticated={this.state.isAuthenticated}
        />
        <section className="section">
          <div className="container">
            {this.state.messageName && this.state.messageType &&
              <Message
                messageName={this.state.messageName}
                messageType={this.state.messageType}
                removeMessage={this.removeMessage} 
              />
            }
            <div className="columns">
              <div className="column is-half">
                <br/>
                <Switch>
                  <Route exact path='/' render={() => (
                    <Spotify
                    userId={this.state.id}
                    menu={this.state.menu}
                    onConnectWithSpotify={this.onConnectWithSpotify}
                    spotifyToken={this.state.spotifyToken}
                    message={this.message}
                    //removeMessage={this.removeMessage} 
                    />
                  )} />

Message.jsx:

import React from 'react';    
    const Message = (props) => {
      return (
        <div className={`notification is-${props.messageType}`}>
          <button className="delete" onClick={()=>{props.removeMessage()}}></button>
          <span>{props.messageName}</span>
        </div>
      )
    };

    export default Message;

单击按钮时如何调用 this.props.message('You linked your Spotify account!', 'success')

handleRedirect 未绑定到组件实例,这可能是它无法正常工作的原因尝试绑定它或将其写为箭头函数:

handleRedirect = event => {
  // ...
}

添加event.preventDefault()后问题解决了,像这样:

  handleRedirect(event) {
    event.preventDefault() // <-------------
    this.props.createMessage('You linked your Spotify account!', 'success');
    ...
  }

忘记该行会导致各种问题,例如默认表单请求等。此修复了重定向并允许弹出消息。