2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
id: 5a24c314108439a4d403614e
|
2021-03-05 15:43:24 +00:00
|
|
|
|
title: 定义一个 Action Creator
|
2018-10-10 22:03:03 +00:00
|
|
|
|
challengeType: 6
|
2020-09-07 08:16:17 +00:00
|
|
|
|
forumTopicId: 301441
|
2021-01-13 02:31:00 +00:00
|
|
|
|
dashedName: define-an-action-creator
|
2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --description--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-05 15:43:24 +00:00
|
|
|
|
创建 action 后要将 action 发送到 Redux store,以便它可以更新其状态。 在 Redux 中,可以定义动作创建器来完成此任务, action creator 只是一个返回动作的 JavaScript 函数, 换句话说,action creator 创建表示动作事件的对象。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --instructions--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-05 15:43:24 +00:00
|
|
|
|
定义名为 `actionCreator()` 的函数,该函数在调用时返回 `action` 对象。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --hints--
|
2020-09-07 08:16:17 +00:00
|
|
|
|
|
2021-03-05 15:43:24 +00:00
|
|
|
|
函数 `actionCreator` 应该存在。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
```js
|
|
|
|
|
assert(typeof actionCreator === 'function');
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
|
|
|
|
|
2021-03-05 15:43:24 +00:00
|
|
|
|
运行 `actionCreator` 函数应返回 `action` 对象。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
```js
|
|
|
|
|
assert(typeof action === 'object');
|
|
|
|
|
```
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-05 15:43:24 +00:00
|
|
|
|
返回的 `action` 对象应该有一个值为 `LOGIN` 的 `type` 属性。
|
2020-09-07 08:16:17 +00:00
|
|
|
|
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
|
assert(action.type === 'LOGIN');
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
2020-08-13 15:24:35 +00:00
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
# --seed--
|
|
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
const action = {
|
|
|
|
|
type: 'LOGIN'
|
|
|
|
|
}
|
|
|
|
|
// Define an action creator here:
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --solutions--
|
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
```js
|
|
|
|
|
const action = {
|
|
|
|
|
type: 'LOGIN'
|
|
|
|
|
}
|
|
|
|
|
const actionCreator = () => {
|
|
|
|
|
return action;
|
|
|
|
|
};
|
|
|
|
|
```
|