javascript - React子组件重新渲染而不改变状态

标签 javascript reactjs flux

我正在将一些数据从一个组件传递到另一个组件(父组件到子组件)。输入和按钮单击事件中数据的传递没有任何问题。我通过考虑一些关键事件(是否输入数字)添加了一些验证。当触发与此验证相关的特定功能时,子组件会自动重新渲染。我不明白为什么。这是我的代码。我使用了 Flux 架构。

主父级(发生关键事件的地方)

    const validatebox = (textStatus) => {

    if (textStatus.length > 100) {
      return {
              error: '*status is too long',
            };
    }  else if (textStatus === '') {
      return {
              error: '*status cannot be empty',
            };
    }  else {
      return true;
    }
}


class PaserBox extends React.Component{

      constructor(props) {
            super(props);
            this.state = {
              textStatus: '',
              tags:{},
              showResults: false
            };

      }

      parse = () => {

        let status = this.refs.textinput.getValue();

        if(validatebox(status).error) {
          this.setState({
            textStatus: validatebox(status).error
          });
          return;

        }
        else {

          Actions.SendDataToTag(status);
          this.setState({ showResults: true });
          console.log(status);


        }
          this.clearText();
      };

      clearText = () => {
        document.getElementById('language').value = '';
      };

      handleKey = (e) =>{
        if (e.key === 'Enter') {
            this.parse();
        } 
        else {
          var keycode = e.which;
          if ((e.shiftKey == false && (keycode == 46 || keycode == 8 || keycode == 37 || keycode == 39 || (keycode >= 48 && keycode <= 57)))) {
            this.setState({
                textStatus: 'cannot enter numbers'
            });
          }
          else {
            this.setState({
              textStatus: ''
            });
          }
        }
      };

      handleKeyDown = (e) => {
        if (e.keyCode == 8) {
          this.setState({
              textStatus: ''
          });
        }
      };

      render(){
        return(
          <div>
            <Paper className="row col-xs-12 col-sm-12 col-md-12" style={style} zDepth={1}>
              <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                <TextField
                  fullWidth={true}
                  style={textfieldstyle}
                  errorText={this.state.textStatus}
                  ref="textinput"
                  onKeyPress={this.handleKey}
                  onKeyDown={this.handleKeyDown}
                  hintText="Enter sentence ..."
                  className="col-xs-12 col-sm-12 col-md-12"
                  name="ta"
                  id="language"/>
              </div>
            <div className="col-xs-9 col-sm-9 col-md-9"/>
            <div className="col-xs-3 col-sm-3 col-md-3" style={style_button}>
              <RaisedButton  secondary={true} label="Parse" onTouchTap={this.parse}/>
            </div>
            <div className="col-xs-1 col-sm-1 col-md-1"/>
            </Paper>
            <label style={styles}>Please enter sentences with correct grammar</label>
            <br/>
            { this.state.showResults ?  <div className="row">
                                          <div className="col-md-10">
                                            <ParserTreeBox/>
                                          </div>
                                          <div className="col-md-2">
                                            <ParserTags/>
                                          </div>
                                        </div> : null }
          </div>
        );
      }

}

export default PaserBox;

发生状态变化的子组件

   class ParserTreeBox extends React.Component{

  constructor(props) {
    super(props);
      this.state = {
        data: [],
        taggedData:{}
      }

     this._onChange = this._onChange.bind (this);
  }

  componentWillMount(){
    Store.addChangeListener(this._onChange);
  }

  componentWillUnmount(){
    Store.removeChangeListener(this._onChange);
  }

  _onChange(){
     this.setState({taggedData:Store.getData()});
  }

   render(){
     return(
        <div>
          <div>
            <ParserTree data={this.state.taggedData} />
          </div>
        </div>
     );
   }

}

export default ParserTreeBox;

这里,即使子组件没有更改状态,渲染函数也会被触发。我调试了它们正常工作的通量文件。我遇到这个问题的任何原因

最佳答案

`Here the render function get triggered even though the states are
not changed by the child components

据我了解,您有一个 setState 函数,它会触发重新渲染 PaserBox,并且您不希望它导致重新渲染 PaserBox 的子级 ParserTreeBox

如果是这样,ParserTreeBox重新渲染是很正常的,因为PaserBox的渲染函数包含了ParserTreeBox组件。

当它在 PaserBox 的渲染函数中时,它只是传递数据。但您仍然可以忽略 ParserTreeBox 组件在 ParserTreeBox 端重新渲染 shouldComponentUpdate(nextProps, nextState) 函数。

shouldComponentUpdate(nextProps, nextState){
 return this.state.taggedData == nextState.taggedData ? false : true
}

现在它将在决定该组件的渲染后检查该方法。

关于javascript - React子组件重新渲染而不改变状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40696199/

相关文章:

javascript - 我不明白 Flux 中 Dispatcher.js 的一些语法

javascript - CanJS 右键单击​​事件

javascript - 仅匹配 JavaScript 正则表达式中方括号中的数字,而不匹配前一个单词

javascript - ReactJS 多文件上传和 axios post : Uncaught (in promise) SyntaxError:

javascript - 在悬停时连接 React-Leaflet CircleMarker 和散点图点

javascript - Flux/Alt 未从商店更新 Prop

javascript - 通过单击其他区域(包括其他下拉菜单)关闭下拉菜单

javascript - 页面加载时隐藏打印时显示

css - 显示和修改 JSON 数据(显示在表格中)使用 React JS

reactjs - 如何保留 "just hidden"组件的状态