【问题标题】:if else statement in render?渲染中的 if else 语句?
【发布时间】:2020-10-03 03:38:23
【问题描述】:

我的代码遇到了一些问题,我希望用户在点击“登录”后被带到两个特定页面,前提是他们之前尚未完成该过程。这两页,如下:

this.props.history.push('/decision-style');
this.props.history.push('/area-of-expertise');

它的工作原理是,如果他们已经经历了这两个页面的过程,我希望他们不要再经历它,而只是被重定向到我们的新闻页面:

this.props.history.push('/news');

如果他们之前经历过这个过程,那么它已经在MongoDB中的“decisionStyle”和“role”文档中添加了他们的信息

This is /area-of-expertise. Only want them to see this, and /decision-style if they haven't done this before, and therefore, their info isn't in Mongo

我想我可以在渲染中创建一个 if...else 语句来做一些类似于我想要实现的事情。但是,这行不通,所以我在下面有这段代码:

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {fact: null,
      badge: null,
      isLoaded: false,
      error: null,
      showRegistration: false,
      userAuthFlow: false,
      userData: {},
    }
  }

render() {
  const self = this;
  console.log(this.state.userData.decisionStyle);
  // Create Registration Form
  function RegistrationFormModal(props) {
    return (
      <Modal
        {...props}
        aria-labelledby="contained-modal-title-vcenter"
        centered
      >
        <Modal.Header>
          <Modal.Title id="contained-modal-title-vcenter">
          Sign Up
            <button className="closeBtn" onClick={self.handleCloseRegistration}></button>
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Registration/>
        </Modal.Body>
      </Modal>
    );
  }

  // Login page

  const {error, isLoaded, fact} = this.state;

  if (error) {
    return (
      <div>
 Error: {error.messages}
      </div>
    );
  } else if (!isLoaded) {
    return (
      <Spinner style={{'width': '200px', 'height': '200px', 'font-size': '50px'}} animation="border"/>
    );
  } else {
    return (
      <div id="Login">
        <Fade top>
          <h1 style={{'font-size': '50px'}}>CRCounter
          </h1>
          <p style={{'font-size': '32px'}}> {JSON.parse(JSON.stringify(fact.fact))}</p>
          <p> - {JSON.parse(JSON.stringify(fact.author))} - </p>
        </Fade>
        <Fade bottom>
          <div id="form">
            <form>

            </form>

            <button className="confirmBtn" userAuthFlow={self.state.userData.role !== null && self.state.userData.decisionStyle !== null ? true : false}onClick = {this.handleClick}>Sign in</button>
            <a id = "register" onClick={this.handleShowRegistration}>Don't have an account?</a>

            <p id = "registerNote" > You won't be able to access most parts of the platform without an account! </p>
          </div>
        </Fade>
        <RegistrationFormModal
          show={this.state.showRegistration}
        />
      </div>

    );
  }
}

我创建的下面的代码主要负责尝试实现我想要的,但它不起作用,不知道为什么,因为我有点 React 菜鸟.. 哈哈

<button className="confirmBtn" userAuthFlow={self.state.userData.role !== null && self.state.userData.decisionStyle !== null ? true : false}onClick = {this.handleClick}>Sign in</button>

其余代码(以及更新的代码)...

/* eslint-disable require-jsdoc */
import React, {Component} from 'react';
import './Login.css';
import Fade from 'react-reveal/Fade';
import Spinner from 'react-bootstrap/Spinner';
import axios from 'axios';
import Modal from 'react-bootstrap/Modal';
import Registration from './Registration';

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {fact: null,
      badge: null,
      error: null,
      fact: null,
      isLoaded: false,
      showRegistration: false,
      userAuthFlow: false,
      userData: {},
    }
  }
handleClick = () => {
  this.props.history.push('/decision-style');
}

// Registration form
handleShowRegistration = () => {
  this.props.history.push('/news');
}


handleCloseRegistration = () => {
  this.setState({showRegistration: false});
}

componentDidMount(sub) {
  axios.get('/services/getuserdata', {
      params: {ID: sub},
    })
        .then((response) => {
          this.setState({userData: response.data});
        });

  // Get the facts that will be displayed under the CRCounter logo
  function getFacts() {
    return axios.get('/services/facts');
  };

  // Get the welcome badge for the user if they signded up successfully for the platform
  function getBadge() {
    return axios.get('/services/badge', {
      params: {
        name: 'welcome',
      },
    });
  }


  Promise.all([getFacts(), getBadge()])
      .then((results) => {
        const responseOne = results[0].data;
        const responseTwo = results[1].data;
        this.setState({
          isLoaded: true,
          fact: responseOne,
          badge: responseTwo,
        });
      })
      .catch((error) => {
        this.setState({
          isLoaded: true,
          fact: {author: '', fact: ''}});
      });
}

handleClick() {};
handleCloseRegistration() {};
handleShowRegisteration() {};

render() {
  const { error, isLoaded, fact, showRegistration, userData } = this.state;
  const flow = userData.role && userData.decisionStyle;
  const parse = (str) => JSON.parse(JSON.stringify(str));
  // Create Registration Form
  const RegistrationFormModal = (props) => {
      return (
        <Modal
          aria-labelledby="contained-modal-title-vcenter"
          centered
          {...props}
        >
          <Modal.Header>
            <Modal.Title id="contained-modal-title-vcenter">
            Sign Up
              <button
                className="closeBtn"
                onClick={this.handleCloseRegistration}
              >
                Close Button
              </button>
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Registration />
          </Modal.Body>
        </Modal>
      );
    };

  // Login page
  if (error) {
    return (
      <div>
 Error: {error.messages}
      </div>
    );
  } else if (!isLoaded) {
    return (
      <Spinner style={{'width': '200px', 'height': '200px', 'font-size': '50px'}} animation="border"/>
    );
  } else {
     return (
      <div id="Login">
        <Fade top>
          <h1 style={{ 'font-size': '50px' }}>CRCounter</h1>
          <p style={{ 'font-size': '32px' }}>{parse(fact.fact)}</p>
          <p> - {parse(fact.author)} - </p>
        </Fade>
        <Fade bottom>
          <div id="form">
            <form>

            </form>
            <button
              className="confirmBtn"
              onClick={this.handleClick}
              userAuthFlow={flow}
            >
              Sign in
            </button>
            <a
              id="register"
              onClick={this.handleShowRegistration}
            >
              Don't have an account?
            </a>
            <p id="registerNote" >
              You won't be able to access most parts of the platform without an account!
            </p>
          </div>
        </Fade>
        <RegistrationFormModal show={showRegistration} />
      </div>
    );
  }
}}

export default Login;

【问题讨论】:

    标签: reactjs mongodb button


    【解决方案1】:

    不是检查虚假值,而是检查真实值。

    这里,如果我们有role && decisionStyle 则为真,否则为假。

    如果两个操作数都为真,则逻辑与运算符 (&&) 返回真,否则返回假。

    self.state.userData.role && self.state.userData.decisionStyle
    

    【讨论】:

      【解决方案2】:

      你的情况的逻辑有点不对劲。它应该类似于userData.role &amp;&amp; userData.decisionStyle;。我还冒昧地解构了你的一些代码,使用箭头函数,删除self,以及其他一些事情!

      更新

      class Login extends Component {
         constructor(props) {
          super(props);
      
          this.state = {
            badge: null,
            error: null,
            fact: null,
            isLoaded: false,
            showRegistration: false,
            userAuthFlow: false, // do you need this?
            userData: {},
          };
        }
      
        componentDidMount() {
           // existing code here
        }
      
        handleClick = () => {
          const { history } = this.props;
          const flow = userData.role && userData.decisionStyle;
          history.push(flow ? '/news' : '/decision-style');
        }
      
        handleShowRegistration = () => {
          this.setState({ showRegistration: true });
        }
      
      
        handleCloseRegistration = () => {
          this.setState({ showRegistration: false });
        }
        
        render() {
          const { error, isLoaded, fact, showRegistration, userData } = this.state;
          const parse = (str) => JSON.parse(JSON.stringify(str));
      
          // Create Registration Form
          const RegistrationFormModal = (props) => {
            return (
              <Modal
                aria-labelledby="contained-modal-title-vcenter"
                centered
                {...props}
              >
                <Modal.Header>
                  <Modal.Title id="contained-modal-title-vcenter">
                  Sign Up
                    <button
                      className="closeBtn"
                      onClick={this.handleCloseRegistration}
                    >
                      Close Button
                    </button>
                  </Modal.Title>
                </Modal.Header>
                <Modal.Body>
                  <Registration />
                </Modal.Body>
              </Modal>
            );
          };
      
          // Login page
          if (error) return <div>Error: {error.messages}</div>;
          if (!isLoaded) return (
            return (
              <Spinner
                animation='border'
                style={{
                  font-size: '50px',
                  height: '200px',
                  width: '200px',
                }}
              />
            );
          );
      
          return (
            <div id="Login">
              <Fade top>
                <h1 style={{ 'font-size': '50px' }}>CRCounter</h1>
                <p style={{ 'font-size': '32px' }}>{parse(fact.fact)}</p>
                <p> - {parse(fact.author)} - </p>
              </Fade>
              <Fade bottom>
                <div id="form">
                  <form>
      
                  </form>
                  <button
                    className="confirmBtn"
                    onClick={this.handleClick}
                  >
                    Sign in
                  </button>
                  <a
                    id="register"
                    onClick={this.handleShowRegistration}
                  >
                    Don't have an account?
                  </a>
                  <p id="registerNote" >
                    You won't be able to access most parts of the platform without an account!
                  </p>
                </div>
              </Fade>
              <RegistrationFormModal show={showRegistration} />
            </div>
          );
        }
      }
      

      【讨论】:

      • 您好,感谢您的回复!该代码确实有意义,我尝试实现它,但遗憾的是仍然无法正常工作。我可能在代码中的其他地方遗漏了一些东西,所以我也会发布其余的代码
      • 我更新了它。我之前没有注意到您尝试将 userAuthFlow 对象传递给本机 button 元素。这真的不会给你你正在寻找的行为,所以我把逻辑移到了handleClick 方法。如果用户之前已经完成了流程,它会将他们推送到/news 视图。如果没有,它会将它们推送到/decision-style 视图。
      • 如果有效,请将其标记为答案!谢谢。 :)