在React中将用户状态传递给子组件

时间:2018-05-22 18:04:27

标签: reactjs react-props

我有一个父组件,它获取用户状态(登录或未登录),并且应该能够将此状态传递给子组件,并根据他们是否登录显示链接。但是,我将loggedIn状态传递给子组件时遇到问题,因此可以根据用户状态显示或隐藏链接:

父组件

class VideoPlayer extends React.Component {
  constructor (props) {
    super(props)
    this.state = {

    }
  }

  async componentDidMount () {
    if (this.md.mobile()) {
      this.setState({ blocking: 'mobile' })
    } else if (this.browser.name === 'ie' || this.browser.name === 'edge') {
      this.setState({ blocking: 'unsupported' })
    } else {
      try {
        const userData = await superagent.get('/api/user')

        if (!userData.error) {
          this.setState({ user: userData.body })
        }
        const loggedIn = userData.body.success <==RETURNS FALSE IF USER IS LOGGED OUT AND "UNDEFINED" IF USER IS LOGGED IN
        console.log(loggedIn)
      } catch (err) {
        console.log('Could not fetch user.', err)
      }

      this.fetchData()
    }
  }

  /**
   * render
   */

  render () {
    return (
      <div className='video-player-container'>
        { this.state.blocking === 'paywall' &&
          <Paywall
            bgImgUrl={this.props.imageUrl('paywall-bg.png' )}
            logoUrl={this.props.imageUrl('logo.png')}
            loggedIn={!!this.state.user && this.state.user.success === undefined}
            {...this.props}
          />
        }
      </div>
    )
  }
}

子组件

function Paywall (props) {
  const { iconHrefs, logoUrl, bgImgUrl, config } = props

  return (
    <div
      className='blocking-paywall'
      style={{ backgroundImage: `url(${bgImgUrl})` }}>
      <div className='container'>
        <div className='logo'>
          <img src={logoUrl} />
        </div>

        <h1 className='heading lg'>{content.heading}</h1>

        <div className='message'>
          <div className='subpara'>
            content
          </div>
          <div className='subpara'>
            catchphrase
          </div>
        </div>

        <div className='login'>
          { !props.loggedIn &&  <==SHOULD ONLY SHOW LOGIN LINK IF USER IS NOT LOGGED IN
            <p>already a member?<a href='/login'>Login</a></p>
          }
        </div>
      </div>
    </div>
  )
}

2 个答案:

答案 0 :(得分:0)

你必须将loggedIn作为支柱传递给paywall,因为你不能将它作为父组件的支柱,所以{... this.props}是不够的。

答案 1 :(得分:0)

首先,您没有将loggedIn属性传递给您的子组件

<Paywall
        bgImgUrl={this.props.imageUrl('paywall-bg.png' )}
        logoUrl={this.props.imageUrl('logo.png')}
        {/* How did you expect child component to get loggedIn?*/}
        loggedIn={!!this.state.user && this.state.user.success === undefined}
        {...this.props} 
      />

然后您的Paywall无状态组件。它没有实例,您不能在渲染方法中使用this

  <div className='login'>
      { !props.loggedIn &&  <==SHOULD ONLY SHOW LOGIN LINK IF USER IS NOT LOGGED IN
        <p>already a member?<a href='/login'>Login</a></p>
      }
    </div>