调用 this.props.message() onClick

Posted

技术标签:

【中文标题】调用 this.props.message() onClick【英文标题】:Call this.props.message() onClick 【发布时间】:2020-02-28 17:58:11 【问题描述】:

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

但它只在componentDidMount()内部有效,在handleRedirection()无效,如下面的cmets所示:

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')

【问题讨论】:

在 App.jsx 文件中 - 函数定义为“消息”,函数在 props 中传递为this.createMessage 这是一个错字,抱歉。固定的。这不是问题,因为它在 componentdidMount() 内部工作 能否通过评论window.location查看。 做到了。不起作用,因为不会发生重定向到 spotify 服务器并返回。 【参考方案1】:

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

handleRedirect = event => 
  // ...

【讨论】:

this.props.message 仍然无法正常工作。此外,handleRedirect 可以使用我上面的代码进行工作和重定向。 您可以使用codesandbox.io/s 并在其中放置一个工作示例吗?这样会更容易使用!【参考方案2】:

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

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

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

【讨论】:

以上是关于调用 this.props.message() onClick的主要内容,如果未能解决你的问题,请参考以下文章

I/O 模型详解

五种I/O模型

Linux(程序设计):62---定时机制之I/O复用系统调用的超时参数

数组 / 伪数组 判断及方法调用 (权威指南笔记)

浅谈I/O多路复用技术

Pyspark--调用 o50.parque 时出错