Call this.props.message()onClick

问题描述 投票:0回答:2

我已将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')

javascript reactjs spotify
2个回答
1
投票

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

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

0
投票

当我添加event.preventDefault()时,问题已解决,如下所示:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.