首页 > 解决方案 > 条件渲染不起作用,因为尚未定义变量

问题描述

我正在尝试进行条件渲染以在我的 React 应用程序中显示编辑和删除按钮。

<div>
        {author_id === user_id &&
        <Container>
        <Row xs="2">
        <Col><Button color="primary" size="sm">Edit</Button></Col>
        <Col><Button color="danger" size="sm">Delete</Button></Col>
        </Row>
        </Container>
        }}
 </div>

我得到了'author_id' is not defined'user_id' is not defined因为album_id它正在从我的数据库中获取数据,componentDidMount()user_id从另一个组件的 Context.Provider 获取数据。

componentDidMount() {
      const { match: { params} } = this.props;
      console.log('COMPONENT HAS MOUNTED');

      fetch(`http://localhost:8000/albums/${params.albumId}`)
        .then((response) =>
          response.json())
        .then((data) => {
              this.setState({ albums : data });
            }).catch((error) => {
                console.log("Error " + error)
              })
    }

    render() {
        if(this.state.albums[0]){
        let author_id = this.state.albums[0].author;
        }
        if(this.context.user){
        let user_id = this.context.user.sub;
      }

    Album.contextType = Auth0Context;

那么我该怎么做才能使这段代码工作,因为这两个变量没有立即具有值?

标签: javascriptreactjs

解决方案


您需要检查两者user_id是否author_id为真,然后检查它们是否相同,然后渲染按钮。

这样的事情应该做你想做的事:

render() {
    const user_id = this.context.user ? this.context.user.sub : null;
    const author_id = this.state.albums[0] ? this.state.albums[0].author : null;
    const shouldRenderButton = user_id && author_id && user_id === author_id;

    return (
        ...
        { shouldRenderButton && <div>...</div> }
        ...
    )
}

推荐阅读