2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: 5a24c314108439a4d403614c
|
2021-03-05 08:43:24 -07:00
|
|
|
title: 从 Redux Store 获取状态
|
2018-10-10 18:03:03 -04:00
|
|
|
challengeType: 6
|
2020-09-07 16:16:17 +08:00
|
|
|
forumTopicId: 301443
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: get-state-from-the-redux-store
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-03-05 08:43:24 -07:00
|
|
|
Redux store 对象提供了几种与之交互的方法, 比如,可以使用 `getState()` 方法检索 Redux store 对象中保存的当前 `state`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-03-05 08:43:24 -07:00
|
|
|
在代码编辑器中可以将上一个挑战中的代码更简洁地重写, 在 `store` 中使用 `store.getState()` 检索`state`,并将其分配给新变量 `currentState`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2021-03-05 08:43:24 -07:00
|
|
|
Redux store 的 state 应该有一个初始值 5。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(store.getState() === 5);
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
|
|
|
|
2021-03-05 08:43:24 -07:00
|
|
|
应该存在一个变量 `currentState`,并为其分配 Redux store 的当前状态。
|
2020-09-07 16:16:17 +08:00
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
(getUserInput) =>
|
|
|
|
assert(
|
|
|
|
currentState === 5 && getUserInput('index').includes('store.getState()')
|
|
|
|
);
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-08-13 17:24:35 +02:00
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
const store = Redux.createStore(
|
|
|
|
(state = 5) => state
|
|
|
|
);
|
|
|
|
|
|
|
|
// Change code below this line
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
|
|
|
const store = Redux.createStore(
|
|
|
|
(state = 5) => state
|
|
|
|
);
|
|
|
|
|
|
|
|
// Change code below this line
|
|
|
|
const currentState = store.getState();
|
|
|
|
```
|