* Improved the translation * Improved the translation * Improved the translation * Improved the translation * Improved the translation
7.2 KiB
7.2 KiB
id, title, challengeType, isRequired, videoUrl, localeTitle
| id | title | challengeType | isRequired | videoUrl | localeTitle |
|---|---|---|---|---|---|
| 5a24c314108439a4d4036154 | Combine Multiple Reducers | 6 | false | Объединение нескольких редукторов |
Description
createStore() . Чтобы объединить несколько редукторов вместе, в Redux есть метод combineReducers() . Этот метод принимает объект как аргумент, в котором вы определяете свойства, которые связывают ключи с конкретными функциями редуктора. Имя, которое вы задаёте ключам, будет использоваться Redux как имя для связанной части состояния. Как правило, хорошей практикой является создание редуктора для каждой части состояния приложения, когда они являются особенными или уникальными в некотором роде. Например, в приложении для заметок с аутентификацией пользователя один редуктор может обрабатывать аутентификацию, а другой - текст и заметки, которые пользователь отправляет. Для такого приложения мы можем написать метод combineReducers() следующим образом: const rootReducer = Redux.combineReducers ({Теперь ключ
auth: authenticationReducer,
notes: notesReducer
});
notes будет содержать все состояние, связанное с нашими заметками и обрабатываемое нашим notesReducer . Так можно создать несколько редукторов для управления более сложным состоянием приложения. В этом примере состояние, находящееся в хранилище Redux, будет тогда единственным объектом, содержащим свойства auth и notes . Instructions
counterReducer() и authReducer() , а также хранилище Redux. Завершите написание функции rootReducer() , используя Redux.combineReducers() . Назначьте counterReducer ключу с именем count и authReducer - ключу с именем auth . Tests
tests:
- text: <code>counterReducer</code> должен увеличивать и уменьшать <code>state</code> .
testString: 'assert((function() { const initalState = store.getState().count; store.dispatch({type: INCREMENT}); store.dispatch({type: INCREMENT}); const firstState = store.getState().count; store.dispatch({type: DECREMENT}); const secondState = store.getState().count; return firstState === initalState + 2 && secondState === firstState - 1 })(), "The <code>counterReducer</code> should increment and decrement the <code>state</code>.");'
- text: <code>authReducer</code> должен переключать <code>state</code> <code>authenticated</code> между <code>true</code> и <code>false</code> .
testString: 'assert((function() { store.dispatch({type: LOGIN}); const loggedIn = store.getState().auth.authenticated; store.dispatch({type: LOGOUT}); const loggedOut = store.getState().auth.authenticated; return loggedIn === true && loggedOut === false })(), "The <code>authReducer</code> should toggle the <code>state</code> of <code>authenticated</code> between <code>true</code> and <code>false</code>.");'
- text: 'Хранилище <code>state</code> должно иметь два ключа: <code>count</code> , который содержит число и <code>auth</code> , который содержит объект. Объект <code>auth</code> должен иметь свойство <code>authenticated</code> , которое содержит логическое значение.'
testString: 'assert((function() { const state = store.getState(); return typeof state.auth === "object" && typeof state.auth.authenticated === "boolean" && typeof state.count === "number" })(), "The store <code>state</code> should have two keys: <code>count</code>, which holds a number, and <code>auth</code>, which holds an object. The <code>auth</code> object should have a property of <code>authenticated</code>, which holds a boolean.");'
- text: '<code>rootReducer</code> должен быть функцией, которая объединяет <code>counterReducer</code> и <code>authReducer</code> .'
testString: 'getUserInput => assert((function() { const noWhiteSpace = getUserInput("index").replace(/\s/g,""); return typeof rootReducer === "function" && noWhiteSpace.includes("Redux.combineReducers") })(), "The <code>rootReducer</code> should be a function that combines the <code>counterReducer</code> and the <code>authReducer</code>.");'
Challenge Seed
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const counterReducer = (state = 0, action) => {
switch(action.type) {
case INCREMENT:
return state + 1;
case DECREMENT:
return state - 1;
default:
return state;
}
};
const LOGIN = 'LOGIN';
const LOGOUT = 'LOGOUT';
const authReducer = (state = {authenticated: false}, action) => {
switch(action.type) {
case LOGIN:
return {
authenticated: true
}
case LOGOUT:
return {
authenticated: false
}
default:
return state;
}
};
const rootReducer = // определите здесь корневой редуктор
const store = Redux.createStore(rootReducer);
Solution
// solution required