参考
-
Context API
使用步骤
将初始状态传递给
React.createContext
。这个方法会返回一个带有Provider
和Consumer
的对象。- 使用
Provider
组件包裹在组件树的最外层,并接收一个 value 属性。value 属性可以是任何值。 - 使用
Consumer
组件,在组件树中Provider
组件内部的任何地方都能获取到状态的子集。
router
三种实现路由的方式
- window.location.hash
- window.location.pathname
- window.history.pushstate(x,x,x)
第3种需要后端将所有路径都指向首页。
生命周期
嵌套组件在首次渲染时的生命周期如下:
触发App的setstate事件后,执行如下:
触发parent的setState,执行如下:
child组件自身的setState,执行如下:
1、**如图:完成前的顺序是从根部到子部,完成时时从子部到根部。(类似于事件机制)
2、每个组件的红线(包括初次和更新)生命周期时一股脑执行完毕以后再执行低一级别的红线生命周期。
3、**第一级别的组件setState是不能触发其父组件的生命周期更新函数,只能触发更低一级别的生命周期更新函数。
一般调用setState后,react的生命周期函数调用顺序如下:shouldComponentUpdate->componnetWillUpdate->render->componentDidUpdate,若是子组件,在componnetWillUpdate之前还会调用componentWillReceiveProps。
componentWillReceiveProps
A、开始前首先需要知道componentWillReceiveProps函数有一个参数nextProps
,它是一个 { 对象 } ,从单词就可以看出它是update时候(也就是下一次)父组件传递过来的props。
B、还要知道 “第一条中” 所讲解的有些生命周期函数只执行一次,而有的执行多次,其中componentWillReceiveProps执行多次,而constructor等执行一次。
C、还需知道在子组件中每次传递过来的this.props对象其实和componentWillReceiveProps的nextProps是一样的,都是最新的。
D、由”第一条”得知: componentWillReceiveProps生命周期是在更新子组件最先执行的,优先于compoentWillUpdate,更优先于render。
E、render函数里不能使用setState(),否则会造成死循环。
但由于componentWillReceiveProps
是最先执行的,所以在其内可以setState({}),在接下来的render中能拿到最新的state后值
使用场景1:在constructor函数中初始化了某个state,必须用 componentWillReceiveProps 来更新state,以便render时为新的state值
使用场景2:充当vue中的watch作用,监听props.value发生变化后执行某个操作,如下:
componentWillReceiveProps(nextProps) {
// this.props中的值是旧值
// nextProps中的值是新值
const { value: oldValue } = this.props;
const { value: newValue } = nextProps;
if (newValue !== oldValue) {
// TODO...
}
}
总结:大部分情况下,componentWillReceiveProps
生命周期函数是没用的,即可以略去不写, 但是在constructor函数中初始化了某个state,必须用 componentWillReceiveProps 来更新state,不可省去,否则render中的state将得不到更新。 同时如果您想在子组件监听watch值变化做处理,也可以用到componentWillReceiveProps
sholdComponentUpdate
接收两个参数,nextProps和nextState,允许我们手动的自定义判断组件是否需要更新,reture false则不需要更新。可以根据组件的实际应用场景设置函数合理的返回值帮助我们避免不必要的更新,阻止render的调用。
CSS方案
- classNames