首页 > 解决方案 > 如何在条件下添加 2 个链接?反应JS

问题描述

我想为 2 个不同的语言页面添加 2 个链接重定向:比如当我完成电子邮件并且输入应该重定向到 /signup 或 /inscription。

handleSubmit = () => {
const { lang, email } = this.state
const { search } = this.props
const { lang } = this.state

if (isEmailValid(email)) {
  if (search) {
    window.location =
      'https://example.com/inscription' + search + '&email=' + email
  } else {
    window.location = 'https://example.com/inscription?email=' + email
  }
} else {
  this.setState({
    error: lang.startBanner.error,
  })
}

}

实际上它只重定向到FR页面和EN页面上的/inscription。我试过这个:

if (search) {
    window.location =
    this.state.lang === 'fr' ? 'https://example.com/inscription' : 'https://example.com/signup' + search + '&email=' + email
      // 'https://example.com/inscription' + search + '&email=' + email

  } else {
    // window.location = 'https://example.com/inscription?email=' + email
    window.location = this.state.lang === 'fr' ? 'https://example.com/inscription' : 'https://example.com/signup' + email
  }
    lang: fr,
    search: '',
    email: '',
    error: '',
    windowWidth: undefined,
  }

  componentDidMount() {
    if (typeof window !== 'undefined' && window) {
      this.handleResize()
      window.addEventListener('resize', this.handleResize)
      this.setState({
        lang: window.location.pathname.includes('/fr') ? fr : en,
        search: window.location.search ? window.location.search : '',
      })
    }
  }```

标签: javascriptreactjsgatsby

解决方案


这应该工作

window.location = this.state.lang === 'fr' ? 'https://example.com/inscription' : 'https://example.com/signup'

处理提交:

  handleSubmit() {
    const { lang, email, search } = this.state;
    const url = this.state.url + (this.state.lang === "fr" ? "inscription" : "signup")
    if (this.isEmailValid(email)) {
      if (search) {
        window.location = url + search + "&email=" + email;
      } else {
        window.location = `${url}?email=` + email;
      }
    } else {
      this.setState({
        error: lang.startBanner.error
      });
    }
  }

我还更新了示例


推荐阅读