--- id: 5a24c314108439a4d4036144 title: Use Provider to Connect Redux to React challengeType: 6 isRequired: false forumTopicId: 301435 localeTitle: Использовать Провайдер для подключения Redux к действию --- ## Description
В последней задаче вы создали хранилище Redux для обработки массива сообщений и создали действие для добавления новых сообщений. Следующим шагом будет предоставление доступа React к хранилищу Redux и действия, необходимые для отправки обновлений. React Redux предоставляет пакет react-redux для выполнения этих задач. React Redux предоставляет небольшой API с двумя ключевыми функциями: Provider и connect . Другая проблема connect . Provider - это оболочка из React Redux, которая обертывает ваше приложение React. Затем этот обертку позволяет вам получить доступ к функциям store Redux и функции dispatch во всем дереве компонентов. Provider берет два реквизита, магазин Redux и дочерние компоненты вашего приложения. Определение Provider для компонента приложения может выглядеть так:
<Магазин-провайдер = {store}>
<Приложение />
</ Provider>
## Instructions
The code editor now shows all your Redux and React code from the past several challenges. It includes the Redux store, actions, and the DisplayMessages component. The only new piece is the AppWrapper component at the bottom. Use this top level component to render the Provider from ReactRedux, and pass the Redux store as a prop. Then render the DisplayMessages component as a child. Once you are finished, you should see your React component rendered to the page. Note: React Redux is available as a global variable here, so you can access the Provider with dot notation. The code in the editor takes advantage of this and sets it to a constant Provider for you to use in the AppWrapper render method.
## Tests
```yml tests: - text: The AppWrapper should render. testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').length === 1; })()); - text: The Provider wrapper component should have a prop of store passed to it, equal to the Redux store. testString: getUserInput => assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return getUserInput('index').replace(/\s/g,'').includes(''); })()); - text: DisplayMessages should render as a child of AppWrapper. testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('AppWrapper').find('DisplayMessages').length === 1; })()); - text: The DisplayMessages component should render an h2, input, button, and ul element. testString: assert((function() { const mockedComponent = Enzyme.mount(React.createElement(AppWrapper)); return mockedComponent.find('div').length === 1 && mockedComponent.find('h2').length === 1 && mockedComponent.find('button').length === 1 && mockedComponent.find('ul').length === 1; })()); ```
## Challenge Seed
```jsx // Redux Code: const ADD = 'ADD'; const addMessage = (message) => { return { type: ADD, message } }; const messageReducer = (state = [], action) => { switch (action.type) { case ADD: return [ ...state, action.message ]; default: return state; } }; const store = Redux.createStore(messageReducer); // React Code: class DisplayMessages extends React.Component { constructor(props) { super(props); this.state = { input: '', messages: [] } this.handleChange = this.handleChange.bind(this); this.submitMessage = this.submitMessage.bind(this); } handleChange(event) { this.setState({ input: event.target.value }); } submitMessage() { const currentMessage = this.state.input; this.setState({ input: '', messages: this.state.messages.concat(currentMessage) }); } render() { return (

Type in a new Message:


    {this.state.messages.map( (message, idx) => { return (
  • {message}
  • ) }) }
); } }; const Provider = ReactRedux.Provider; class AppWrapper extends React.Component { // render the Provider here // change code above this line }; ```
### After Tests
```jsx ReactDOM.render(, document.getElementById('root')) ```
## Solution
```jsx // Redux Code: const ADD = 'ADD'; const addMessage = (message) => { return { type: ADD, message } }; const messageReducer = (state = [], action) => { switch (action.type) { case ADD: return [ ...state, action.message ]; default: return state; } }; const store = Redux.createStore(messageReducer); // React Code: class DisplayMessages extends React.Component { constructor(props) { super(props); this.state = { input: '', messages: [] } this.handleChange = this.handleChange.bind(this); this.submitMessage = this.submitMessage.bind(this); } handleChange(event) { this.setState({ input: event.target.value }); } submitMessage() { const currentMessage = this.state.input; this.setState({ input: '', messages: this.state.messages.concat(currentMessage) }); } render() { return (

Type in a new Message:


); } }; const Provider = ReactRedux.Provider; class AppWrapper extends React.Component { // change code below this line render() { return ( ); } // change code above this line }; ```