Files
freeCodeCamp/curriculum/challenges/chinese/03-front-end-libraries/redux/dispatch-an-action-event.chinese.md

2.3 KiB
Raw Blame History

id, title, challengeType, isRequired, forumTopicId, localeTitle
id title challengeType isRequired forumTopicId localeTitle
5a24c314108439a4d403614f Dispatch an Action Event 6 false 301442 分发 Action Event

Description

dispatch方法用于将 action 分派给 Redux store调用store.dispatch()将从 action creator 返回的值发送回 store。 action creator 返回一个具有 type 属性的对象,该属性指定已发生的 action然后该方法将 action 对象 dispatch 到 Redux store根据之前的挑战示例以下内容是等效的并且都 dispatch 类型为LOGIN的 action
store.dispatch(actionCreator());
store.dispatch({ type: 'LOGIN' });

Instructions

代码编辑器中的 Redux store 具有初始化状态对象{login:'false'},还有一个名为loginAction()的 action creator它返回类型为LOGIN的 action然后通过调用dispatch方法将LOGIN的 action dispatch 给 Redux store并传递loginAction()创建的 action。

Tests

tests:
  - text: '调用函数<code>loginAction</code>应该返回一个对象{type:"LOGIN"}。'
    testString: assert(loginAction().type === 'LOGIN');
  - text: 'store 应该初始化一个对象 {login:false}。'
    testString: assert(store.getState().login === false);
  - text: <code>store.dispatch()</code>方法应该被用于 dispatch 一个类型为<code>LOGIN</code>的 action。
    testString: "getUserInput => assert((function() {  let noWhiteSpace = getUserInput('index').replace(/\\s/g,''); return noWhiteSpace.includes('store.dispatch(loginAction())') || noWhiteSpace.includes('store.dispatch({type: \\'LOGIN\\'})') === true })());"

Challenge Seed

const store = Redux.createStore(
  (state = {login: false}) => state
);

const loginAction = () => {
  return {
    type: 'LOGIN'
  }
};

// 在这里 dispatch action

Solution

const store = Redux.createStore(
  (state = {login: false}) => state
);

const loginAction = () => {
  return {
    type: 'LOGIN'
  }
};

// Dispatch the action here:
store.dispatch(loginAction());