-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
60 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,43 @@ | ||
## other apis | ||
# other apis | ||
> 组件还提供了一些额外的 API: | ||
## setState | ||
> 将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件。 | ||
this._updaterQueue(); | ||
|
||
- 视为请求而不是立即更新组件的命令。为了更好的感知性能,React 会延迟调用它,然后通过一次传递更新多个组件 | ||
- React 并不会保证 state 的变更会立即生效 | ||
- setState() 并不总是立即更新组件,它会批量推迟更新 | ||
|
||
## 调用到最新的 state | ||
- 请使用 componentDidUpdate | ||
- setState 的回调函数(setState(updater, callback)),这两种方式都可以保证在应用更新后触发 | ||
|
||
```js | ||
this.setState((state, props) => { | ||
return {counter: state.counter + props.step}; | ||
}); | ||
``` | ||
|
||
~~~ | ||
stateChange 会将传入的对象浅层合并到新的 state 中,例如,调整购物车商品数: | ||
this.setState({quantity: 2}) | ||
这种形式的 setState() 也是异步的,并且在同一周期内会对多个 setState 进行批处理。例如,如果在同一周期内多次设置商品数量增加,则相当于: | ||
Object.assign( | ||
previousState, | ||
{quantity: state.quantity + 1}, | ||
{quantity: state.quantity + 1}, | ||
... | ||
) | ||
后调用的 setState() 将覆盖同一周期内先调用 setState 的值,因此商品数仅增加一次。如果后续状态取决于当前状态,我们建议使用 updater 函数的形式代替: | ||
this.setState((state) => { | ||
return {quantity: state.quantity + 1}; | ||
}); | ||
~~~ | ||
|
||
## forceUpdate | ||
component.forceUpdate(callback) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
# getDerivedStateFromProps | ||
|
||
## 基本用法 | ||
getDerivedStateFromProps 会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。 | ||
它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。 | ||
|
||
## 详细说明 | ||
此方法适用于罕见的用例,即 `state 的值在任何时候都取决于 props` 。 | ||
例如,实现 <Transition> 组件可能很方便,该组件会比较当前组件与下一组件,以决定针对哪些组件进行转场动画。 | ||
派生状态会导致代码冗余,并使组件难以维护。 确保你已熟悉这些简单的替代方案: | ||
|
||
- 如果你需要执行副作用(例如,数据提取或动画)以响应 props 中的更改,请改用 componentDidUpdate。 | ||
- 如果只想在 prop 更改时重新计算某些数据,请使用 memoization helper 代替。 | ||
- 如果你想在 prop 更改时“重置”某些 state,请考虑使组件完全受控或使用 key 使组件完全不受控 代替。 | ||
|
||
此方法无权访问组件实例。如果你需要,可以通过提取组件 props 的纯函数及 class 之外的状态,在getDerivedStateFromProps()和其他 class 方法之间重用代码。 | ||
请注意,不管原因是什么,都会在每次渲染前触发此方法。这与 UNSAFE_componentWillReceiveProps 形成对比,后者仅在父组件重新渲染时触发,而不是在内部调用 setState 时。 |