reactjs - 单击按钮,从localstorage加载一些东西,并在函数外部显示它

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

我不知道这个话题是否有意义,但我基本上想:

  1. 单击一个按钮
  2. 从我的本地存储中加载一些东西
  3. 用加载的东西替换按钮

我现在有

const getToken = (props) => {
    let token = localStorage.getItem("token");
    console.log('token', token);
    return token;

}

const ApiInstruction = (props) => (
    <div>
        <Backdrop show={props.show} clicked={props.modalClosed}/>

        <div className="api-instruction"
             style={{transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
                     opacity: props.show ? '1': '0'}}>
            <button className="api-instruction-button" onClick={() => getToken(props)}>Request Token</button>
            <h4>Instruction on how to use API:</h4>
            <p>bleh</p>
            <p>(click anywhere in grey to close)</p>
        </div>
    </div>
);

单击该按钮会触发getToken函数,但我不知道如何传回结果。

我目前的ApiInstrction电话如下。

<ApiInstruction show={this.state.openApiInsModal} modalClosed={this.BackdropHandler} token={null}/>

如何用通话中的内容替换按钮?它甚至可能吗?

reactjs
3个回答
1
投票

您正在使用无状态功能组件来实现所需的功能。但是,您需要一个状态概念,以便您的组件能够跟踪它们是否已从本地存储中检索到令牌。这就是为什么React中有状态的组件,在这种情况下,你应该使用它,而不是无状态组件。

下面是一个代码示例,说明了状态的使用可能有所帮助。

class ApiInstruction extends Component {
    state = {
    };

    getToken = (props) => {
        let token = localStorage.getItem("token");
        console.log('token', token);
        return token;
    }

    handleClick = (event) => {
        this.setState({token: getToken(this.props);});
    }

    render() {
        if(this.state.token === undefined) {
            return (
                <div>
                    <Backdrop show={props.show} clicked={props.modalClosed}/>

                    <div className="api-instruction"
                         style={{transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
                                 opacity: props.show ? '1': '0'}}>
                        <button className="api-instruction-button" onClick={this.handleClick}>Request Token</button>
                        <h4>Instruction on how to use API:</h4>
                        <p>bleh</p>
                        <p>(click anywhere in grey to close)</p>
                    </div>
                </div>
            );
        } else {
            <p>{this.state.token}</p>
        }
    }
}

如您所见,如果tokenstate信息中定义,则render()方法仅显示所获取的信息。 (即token本身)除非采用,否则显示按钮的初始界面。


1
投票

有点不清楚你在哪里试图显示结果......现在你正在向你的onClick返回一个令牌,它没有做任何事情。您应该将getToken中的标记设置为状态值,然后您可以在任何位置显示它。另外值得注意的是localStorage是异步的,所以你必须处理这个承诺。

state = ({token:''})

const getToken = (props) => {
    localStorage.getItem("token").then(result => {
      console.log('Token: ' + result)
      this.setState({token:result})
    });
}

const ApiInstruction = (props) => (
    <div>
        <Backdrop show={props.show} clicked={props.modalClosed}/>

        <div className="api-instruction"
             style={{transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
                     opacity: props.show ? '1': '0'}}>
            <button className="api-instruction-button" onClick={() => getToken(props)}>Request Token</button>
            {this.state.token != '' && <p>{this.state.token}</p>}
            <h4>Instruction on how to use API:</h4>
            <p>bleh</p>
            <p>(click anywhere in grey to close)</p>
        </div>
    </div>
);

1
投票

您应该使其有状态并保持其状态以有条件地呈现按钮组件

 class ApiInstruction extends Component {
  state = {
    isLocalStorage : false
  }

  handleCLick= () => {
    getToken(this.props)
    this.setState({
      isLocalStorage  : true
    })
  }

  render() {
    const { isLocalStorage } = this.state;
    return(
  <div>
    <Backdrop show={props.show} clicked={props.modalClosed} />

    <div className="api-instruction"
      style={{
        transform: props.show ? 'translateY(0)' : 'translateY(-100vh)',
        opacity: props.show ? '1' : '0'
      }}>
      {!isLocalStorage && <button className="api-instruction-button" onClick={this.handleCLick}>Request Token</button>}
      <h4>Instruction on how to use API:</h4>
      <p>bleh</p>
      <p>(click anywhere in grey to close)</p>
    </div>
  </div>
)
}
© www.soinside.com 2019 - 2024. All rights reserved.