Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如果else不工作,则使用条件渲染器进行反应_Reactjs - Fatal编程技术网

Reactjs 如果else不工作,则使用条件渲染器进行反应

Reactjs 如果else不工作,则使用条件渲染器进行反应,reactjs,Reactjs,我是React的新手,我想询问关于连续记录的问题,我正在制作关于发送消息的项目,我使用验证检查所有字段是否为空,当一个字段为空时,它应该显示消息未发送的错误消息。我使用if-else来呈现错误消息,但它不起作用 这里我添加了我的代码 .... export default class Message extends React.Component { constructor(props){ super(props); this.state = { isL

我是React的新手,我想询问关于连续记录的问题,我正在制作关于发送消息的项目,我使用验证检查所有字段是否为空,当一个字段为空时,它应该显示消息未发送的错误消息。我使用if-else来呈现错误消息,但它不起作用

这里我添加了我的代码

....

export default class Message extends React.Component {
  constructor(props){
    super(props);
      this.state = {
        isLoggedIn: SystemStore.isLoggedIn(),
        profile: ProfileStore.getProfile(),
        fullName: SystemStore.systemUser().fullName,
        site: '',
        email: '',
        phone: '',
        subject: '',
        description: '',
        type: '',
        errorMessage: '',
        errorDialog: '',
        isSubmited: false,
        successMessage: '',
        submitting: false
      };

    this.clearForm = this.clearForm.bind(this);
    this.handleProfileChange = this.handleProfileChange.bind(this);
    this.handleSubjectChange = this.handleSubjectChange.bind(this);
    this.handleMessageChange = this.handleMessageChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleSubmitComplete = this.handleSubmitComplete.bind(this);
    this.handleSubmitError = this.handleSubmitError.bind(this);
  }

  componentDidMount(){
    ProfileStore.addProfileChangeListener(this.handleProfileChange);
      if(!this.state.profile){
        ProfileActions.reload()
      }
      
    MessageStore.addSubmitMessageChangeListener(this.handleSubmitComplete);
    MessageStore.addSubmitMessageFailChangeListener(this.handleSubmitError);
  }    

  componentWillUnmount(){
    ProfileStore.removeProfileChangeListener(this.handleProfileChange);
    MessageStore.removeSubmitMessageChangeListener(this.handleSubmitComplete);
    MessageStore.removeSubmitMessageFailChangeListener(this.handleSubmitError);
  }

  render(){
    return(
      <Layout>
        <div className='hs-dashboard row'>
          <div className='col-md-12'>
            <div className='col-xs-12 col-sm-6 col-md-5'>
              <div className='col-xs-12 hs-message-form'>
                <div className='row hs-message-form-head'>
                  <div className='hs-message-form-logo-container'>
                    <img className='col hs-message-form-logo' src='../../images/gii-logo-black.png'/>
                      <text className='hs-message-form-logo-label'>{T.translate('gii')}</text>
                  </div>
                  <div className='hs-message-form-label'>
                    { T.translate('message.title') }
                  </div>
                  <div className='hs-message-form-label-1'>
                    { T.translate('message.subtitle') }
                  </div>
                </div>
                <div className='row hs-message-form-body'>
                  <form className='hs-message-form-body-content'>
                    <label>
                      { T.translate('message.type') }
                    </label>
                    <select
                      id="subject"
                      value={ this.state.subject }
                      onChange={ this.handleSubjectChange }
                      className="form-control"
                      required="true"
                    >
                      <option value="">{ T.translate('placeholder.selectSubject') }</option>
                      <option value="PRAYER">{ T.translate('message.pray') }</option>
                      <option value="ADDRESS">{ T.translate('message.address') }</option>
                      <option value="VISIT">{ T.translate('message.visit') }</option>
                    </select>
                    <label>
                      {T.translate('message.message')}
                    </label>
                    <textarea
                      type="text"
                      id="description"
                      className="form-control"
                      width=''
                      placeholder={ T.translate('placeholder.message') }
                      onChange={ this.handleMessageChange }
                      value={ this.state.description }
                      required
                    />
                    
                    { this.state.errorDialog && 
                      <div className='hs-message-empty'>
                        { this.state.errorDialog }
                      </div>
                    }

                    { this.state.isSubmited === true ?
                      <div className='hs-message-success'>
                        { this.state.successMessage }
                      </div> : 
                      <div className='hs-message-error'>
                        { this.state.errorMessage }
                      </div>
                    }

                    <LaddaButton
                      loading={ this.state.submitting }
                      onClick={ this.handleSubmit }
                      data-spinner-size={ 30 }
                      data-style={ SLIDE_RIGHT }
                    >
                      { T.translate('action.send') }
                    </LaddaButton>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
      </Layout>
    )
  }

  clearForm(){
    this.setState({ subject: '', description: '' });
  }


  handleProfileChange(){
    this.setState({
      site: ProfileStore.getProfile().primarySite.name,
      email: ProfileStore.getProfile().emailAddresses[0].email,
      phone: ProfileStore.getProfile().contactNumbers[0].countryCode + ProfileStore.getProfile().contactNumbers[0].number
    });
  }

  handleSubjectChange(evt){
    this.setState({ subject: evt.target.value }, () => {
      if(this.state.subject === 'PRAYER') {
        this.setState({ type: 'REQUEST' });
      } else if(this.state.subject === 'ADDRESS') {
        this.setState({ type: 'INFORMATION' });
      } else if(this.state.subject === 'VISIT'){
        this.setState({ type: 'REQUEST' });
      }
    });
  }
    
  handleMessageChange(evt){
    this.setState({ description: evt.target.value });
  }

  handleSubmit(evt) {
    evt.preventDefault();
    var errorDialog;
    if(this.state.subject === ''){
      errorDialog = 'Error:' + T.translate('msg.subjectRequired');
    } else if(this.state.description === ''){
      errorDialog = 'Error:' + T.translate('msg.mailDescriptionRequired');
    }

    this.setState({errorDialog: errorDialog});

    this.handleProfileChange();
    this.handleSubjectChange(evt);
    this.handleMessageChange(evt);
    var messageInfo = {
      fullName: this.state.fullName,
      site: this.state.site,
      email: this.state.email,
      phone: this.state.phone,
      subject: this.state.subject,
      description: this.state.description,
      type: this.state.type
    };

    this.setState({ submitting: true }, () => {
      MessageActions.sendMessage(messageInfo);
    });

    console.log(this.state.isSubmited);
  }

  handleSubmitComplete(){
    this.setState({
      submitting: false,
      isSubmited: true,
      errorMessage: null,
      successMessage: T.translate('msg.mailSent')
    });
    this.clearForm();
  }

  handleSubmitError(){
    this.setState({
      submitting: false,
      isSubmited: false,
      errorMessage: T.translate('msg.mailSentFailed'),
      successMessage: null
    });
  }
}
这是我的action.js

.....
function _sendMessage(messageInfo, callback) {
  jQuery.ajax({
    method: 'POST',
    url: api('supportTickets'),
    contentType: 'application/json',
    data: JSON.stringify(messageInfo) 
  })
  .done(function(messageInfo) {
    callback(null, messageInfo);
  })
  .fail(function(err){
    console.error('Failed to send message : ' + JSON.stringify(err));
    callback(err, null);
  });
}

var MessageActions = {
  sendMessage: function(messageInfo) {
    _sendMessage(messageInfo, function(err, messageInfo) {
      if(err) {
        Dispatcher.dispatch({
          actionType: MessageConstants.PERFOM_SEND_MESSAGE_FAIL
        });
      }
      Dispatcher.dispatch({
        actionType: MessageConstants.PERFORM_SEND_MESSAGE,
        messageInfo
      });
    });
  }
};

module.exports = MessageActions;

您的组件似乎有点复杂。考虑将组件拆分为更小的组件。使用功能组件,我会以类似的方式完成这项任务

function validateForm() {
  // validate form logic here. If it's ok, returns true, otherwise, returns false
}

function Message({ form }) {
  if (!validateForm(form)) {
    return (
      <div>Please, fill the empty fields!!</div>
    )
  }

  return (
    <div>All good. Submit the form!!</div>
  )
}
函数validateForm(){
//在这里验证表单逻辑。如果正确,则返回true,否则返回false
}
函数消息({form}){
如果(!validateForm(表单)){
返回(
请填写空白字段!!
)
}
返回(
一切都好。提交表格!!
)
}

您的表单应负责处理错误。在提交表格时,您应该知道自己的错误

handleSubmit(evt) {
    evt.preventDefault();
    var errorDialog;
    if(this.state.subject === ''){
      errorDialog = 'Error:' + T.translate('msg.subjectRequired');
    } else if(this.state.description === ''){
      errorDialog = 'Error:' + T.translate('msg.mailDescriptionRequired');
    }

   if (errorDialog) {
      this.setState({
         // set your error here
      })
      return;
   }

   
    this.handleProfileChange();
    this.handleSubjectChange(evt);
    this.handleMessageChange(evt);
    var messageInfo = {
      fullName: this.state.fullName,
      site: this.state.site,
      email: this.state.email,
      phone: this.state.phone,
      subject: this.state.subject,
      description: this.state.description,
      type: this.state.type
    };

    this.setState({ submitting: true }, () => {
      MessageActions.sendMessage(messageInfo);
    });

    console.log(this.state.isSubmited);
  }

您在哪里设置此.state.errorMessage?我在你的
handleSubmit
方法中看不到任何地方。@PrateekThapa,我将它设置在handlerSubmiter上,你在哪里调用它?似乎它没有被解雇。您的
addSubmitMessageFailChangeListener
@PrateekThapa的实现有问题,我更新了我的代码,对于addSubmitMessageFaiChangeListener,我添加了我的store.js,当store all listener包括addMessageFailChangeListener时,我不知道到底哪里出了问题。必须在哪里触发?我已经尝试过了,但错误消息现在没有显示,还有其他建议吗?@Pablo,我可以问你一个简单的react.js相关问题吗?如果(this.state.subject==''),我应该移动吗。。。如果(错误对话)?是的。此外,您可能不需要两种状态的
errorDialog
errors
。一个就可以了。代码应该是这样的吗<代码>if(errorDialog){if(this.state.subject==''){errorDialog='错误:'+T.translate('msg.subjectRequired');}else if(this.state.description==''){errorDialog='错误:'+T.translate('msg.mailsdescriptionrequired');}this.setState({errorDialog:errorDialog,errorMessage:T.translate('msg.mailSentFailed')});return;}
handleSubmit(evt) {
    evt.preventDefault();
    var errorDialog;
    if(this.state.subject === ''){
      errorDialog = 'Error:' + T.translate('msg.subjectRequired');
    } else if(this.state.description === ''){
      errorDialog = 'Error:' + T.translate('msg.mailDescriptionRequired');
    }

   if (errorDialog) {
      this.setState({
         // set your error here
      })
      return;
   }

   
    this.handleProfileChange();
    this.handleSubjectChange(evt);
    this.handleMessageChange(evt);
    var messageInfo = {
      fullName: this.state.fullName,
      site: this.state.site,
      email: this.state.email,
      phone: this.state.phone,
      subject: this.state.subject,
      description: this.state.description,
      type: this.state.type
    };

    this.setState({ submitting: true }, () => {
      MessageActions.sendMessage(messageInfo);
    });

    console.log(this.state.isSubmited);
  }