setState是异步的
如果想操作dom一定要在setState的回调里
例子:
获得ul里li元素的个数
import React, { Component } from 'react'; class Test extends Component { constructor(props) { super(props); this.state = { list:[1,2,3], inputValue:'' } } handleChange=(e)=>{ this.setState({ inputValue:e.target.value }) } handleAdd =()=>{ let newList = [...this.state.list] this.setState({ list:[...newList,this.state.inputValue], inputValue:'' },()=>{ // 获取li的个数 let ul = document.querySelectorAll('ul') let childNodes = [...ul][0].childNodes console.log(childNodes.length); }) // 获取li的个数 (错误方法,不应该写在这里,而是写在setState的回调里,因为setState是异步的) let ul = document.querySelectorAll('ul') let childNodes = [...ul][0].childNodes console.log(childNodes.length); } render() { return ( <div> <input value={this.state.inputValue} onChange={this.handleChange} /> <button onClick={this.handleAdd}>添加</button> <ul ref={ul=>this.ul=ul}> { this.state.list.map((v,i)=>{ return <li key={i}>{v}</li> }) } </ul> </div> ); } } export default Test;