本文基于React v16.4.1css
初学react,有理解不对的地方,欢迎批评指正^_^react
一、函数定义组件异步
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
二、类定义组件函数
class Welcome extends Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
这两种方式均可以定义一个组件,区别在于类定义的组件有State和生命周期。另外,还要注意的是组件名称要以大写字母开头。性能
以下,是官网的一个例子:优化
class Clock extends React.Component { constructor(props) { super(props); this.state = {date: new Date()}; } render() { return ( <h2>It is {this.state.date.toLocaleTimeString()}.</h2> ); } }
能够看到,上面的代码在类中添加了constructor()方法,并在其中初始化了this.state 。this
关于constructor() :constructor()方法是类必须有的,若是没写,会自动添加。spa
关于super(props) :super()方法将父类中的this对象继承给子类,添加参数props,就可使用this.props 。code
一、不能直接修改Statecomponent
初始化this.state只能在constructor()里面,修改State要用setState()方法。
二、多是异步的
调用setState
,组件的state并不会当即改变,setState
只是把要修改的状态放入一个队列中,React会优化真正的执行时机,而且React会出于性能缘由,可能会将屡次setState
的状态修改合并成一次状态修改,因此不能用当前的state来计算下一个state。例以下面的写法是错误的:
// Wrong this.setState({ counter: this.state.counter + this.props.increment, });
应改成:
// Correct this.setState((prevState, props) => ({ counter: prevState.counter + props.increment }));
三、state的更新是浅合并的
例如,下面的state中有title和comments两个变量,当调用this.setState({title: 'react'})修改title时,react会把新的title合并进去,不会改变comment。
constructor(props) { super(props); this.state = { title: 'abc', comments: [] }; }
今天遇到了一个问题,react会渲染两次state,一次是初始设置的state,一次是set后的state。
缘由:由于react渲染机制形成组建挂载以前,也就是componentDidMount生命周期以前自动获取了原始的state数据,componentDidMount以后state变化已经没法再次获取了。
解决办法:设置一个state,例如hasFetch: false,在set时把hasFetch设为true,根据hasFetch的值判断是不是set后的值。
END-------------------------------------