反应。组件不按状态更改的顺序呈现

时间:2017-08-14 05:41:04

标签: reactjs virtual-dom

在反应中,假设我有输入组件,其名称为A,B,C。 它们按顺序呈现

render() {
   return(
      <Input name="A" />
      <Input name="B" />
      <Input name="C" />
   );
}

然后我按照 的顺序更改 C A 的状态C 然后 A。 组件 A C 首先按顺序呈现 A < / strong>然后 C 。它们不按状态变化的顺序呈现( C 然后 A

请参阅下面给出的代码段。 我发现输出为

  

设置C的状态

     

设置B的状态

     

设置A的状态

     

渲染A

     

渲染B

     

渲染C.   

class Input extends React.Component {
  
  
	componentWillMount() {
			this.props.addInput(this);
	}
  
  state = {
  	error: false
   }
   
   check() {
   console.log("set state of", this.props.name)
    this.setState({
      error: true
    })
   }

  render() {
  	console.log("Render of", this.props.name)
    return (
      <input   />
    );
  }
}
class Hello extends React.Component {
  
  constructor(props) {
  super(props);
   this.inputs = {};
}

   addInput(component) {
      this.inputs[component.props.name] = component;
      console.log(this.inputs);
    }
   
   checkAll() {
   const inputs = this.inputs;
   Object.keys(inputs).reverse().forEach(name => {
     inputs[name].check()
    });
   }
 
  render() {
    return (
    	<div>
        <Input addInput={(c) => this.addInput(c)} name="A"/>
        <Input addInput={(c) => this.addInput(c)} name="B"/>
        <Input addInput={(c) => this.addInput(c)} name="C"/>
        <button onClick={() => this.checkAll()}>click here</button>
      </div>
    );
  }
}

ReactDOM.render(
  <Hello initialName="World"/>,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

1 个答案:

答案 0 :(得分:1)

这就是JSX默认工作的方式。

如果要按照上次状态更改的顺序呈现组件,则必须将所有组件放入数组或具有componentName: componentInstance的集合,同时具有集合[或数组] componentName: lastUpdated(或数组项{ componentName: string, lastUpdated: Date }),您可以在其中修改每个组件的lastUpdated值,然后按日期值对componentName: componentInstance集合或数组进行排序。

然后只是JSX中的.map