在ReactJS中使用道具有条件地渲染div

时间:2019-05-28 04:20:45

标签: reactjs jsx react-props

我是一个非常新的反应者,在提交帖子回复后我试图显示一条消息,但是没有显示出来。

注意:POST响应正常运行。该消息需要显示app.js中的状态何时更新。似乎状态值仅在页面首次呈现时才传递一次。

APP.JS

class App extends Component {
  status = null;
  submit = async values => {
    const response = await providers.post('/providers/', {
      params: {
        values
      }
    });
    this.status = response.status;
    if (this.status === 200) {
      this.getInitialValues();
      this.myFormRef.reset();
    } else {
      console.log('ERROR: There was an error creating a new Provider');
    }
  };

  render() {
    return (
      <div className='registration-form ui container'>
        <img src={logo} alt={logo} />
        <h1>New Provider Form</h1>
        <Form
          onSubmit={this.submit}
          initialValues={this.getInitialValues()}
          ref={el => (this.myFormRef = el)}
        />
        <Status status={this.status} />
      </div>
    );
  }

STATUS.JS

import React from 'react';
const Status = props => {
  console.log(props.status);
  if (props.status === 200) {
    return <div className='status'>Provider Successfully Registered!</div>;
  } else if (props.status > 200) {
    return <div className='status'>ERROR: Couldn't register new provider</div>;
  } else {
    return null;
  }
};

export default Status;

2 个答案:

答案 0 :(得分:2)

使用状态进行重新渲染

class App extends Component {
  state = {
    status: '',
  };
  submit = async values => {
    const response = await providers.post('/providers/', {
      params: {
        values
      }
    });
    this.setState({
      status: response.status,
    });
    //this.status = response.status;
    if (response.status === 200) {
      this.getInitialValues();
      this.myFormRef.reset();
    } else {
      console.log('ERROR: There was an error creating a new Provider');
    }
  };
  render() {
    return (
     ...
     <Status status = {this.state.status}/>
     ...
    );
  }

答案 1 :(得分:1)

为了在react js中显示任何更新的状态,您必须使用state渲染该变量。因为当您在setState中进行反应时,它会自动重新呈现该组件。 因此,您可以将状态保存为以下状态:

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      status: '',
    };
  }

submit = async (values) => {
    const response = await providers.post('/providers/', {
      params: {
        values
      }
    });
    this.setState({status: response.status},()=>{
       if (this.state.status === 200) {
         this.getInitialValues();
         this.myFormRef.reset();
       } else {
         console.log('ERROR: There was an error creating a new Provider');
       }
    });

  };
render() {
    return (
      <div className='registration-form ui container'>
        <img src={logo} alt={logo} />
        <h1>New Provider Form</h1>
        <Form
          onSubmit={this.submit}
          initialValues={this.getInitialValues()}
          ref={el => (this.myFormRef = el)}
        />
        <Status status={this.state.status} />
      </div>
    );
}

希望这会有所帮助!