条件组件渲染而不使用location.pathname React

时间:2018-01-16 23:59:24

标签: javascript reactjs ecmascript-6 react-redux

我目前正在尝试根据用户当前所在的页面呈现组件。其中一个组件保持不变,其中一个组件将在页面位置确定。我目前正在使用window.location.pathname,但这对我们来说不是理想的行为。

const Container = reduxForm({ form: 'login' })(LoginForm)
const currentLocation = window.location.pathname

const ExtraButtons = () => (
  <div className="row center-xs">
    <div className="col-xs-6 center-xs">
      <Link to={FORGOT_PASSWORD_ROUTE}>Forgot Password?</Link>
    </div>
  </div>
)

const Login = ({ loginStart, error, update, search, address, 
currentUser }) => (
  <div>
    <div className="row center-xs">
      <div className="col-xs-12">
        <img src={logo} className="logo" />
      </div>
    </div>
    <div className="row">
      <div className="col-xs">
        <Container onSubmit={loginStart} />
        {error && (
          <InputError
            visible={error && error !== null}
            errorMessage={error.message}
          />
        )}
        <ExtraButtons />
      </div>
      {currentLocation.includes('/login') ? (
        <div className="row center-xs start-xs col-xs">
          <LocSearch
            updateAddress={update}
            search={search}
            address={address}
          />
        </div>
      ) : currentLocation.includes('/home') ? (
        <div className="col-xs">
          <EmailSearch />
        </div>
      ) : null}
    </div>
  </div>
)

const mapStateToProps = state => {
  const { submitting, currentUser } = state.user
  const { address = '' } = state.locationSearch
  const error = state.error

  return {
    address,
    submitting,
    error,
    currentUser
  }
}

const mapDispatchToProps = {
  loginStart,
  resetError,
  update,
  search
}

export default connect(mapStateToProps, mapDispatchToProps)(Login)

1 个答案:

答案 0 :(得分:0)

我认为在加载脚本时会为currentLocation分配值,而不是在呈现组件时。这是根本原因。您应该在组件中定义currentLocation。