javascript - How does Redux change UI in React? - Stack Overflow

I've been trying hard to wrap my head around this concept but with no luck.The official React tut

I've been trying hard to wrap my head around this concept but with no luck. The official React tutorial is really good but for me it's way too plex and just simply a little bit too hard.

I'm trying to understand Redux and so far I can create actions, reducers, I can dispatch an action and then see how the store state changes after dispatching it. I also managed to understand connect of react-redux and it works perfectly well and I'm able to trigger dispatches from any place in my app. So I think I almost got it figured out. Almost, because here's the elephant in the room - I dispatch the action, I see the Redux state change but HOW DO I CHANGE THE UI?

For example I have text object in my initial state with value Initial text and once a button is clicked I want to change the text to Clicked text and DISPLAY the text somewhere in the UI (let's say on the button).

How do I "access" the Redux state in React and how do I dynamicaly change it?

It seems to be very simple without React, e.g..: / - render function handles everything, I understand everything that happens here.

But on the other side "todo" from official React+Redux tutorial looks like this: .html , it's so sophisticated I have no idea where to look.

The Add Todo button submits a form that dispatches dispatch(addTodo(input.value)) action. The action itself does nothing just increases the ID and passes the text to the store and the reducer just returns the new state. Then how the todo is being rendered on the page? Where? I'm lost at this point. Maybe there are simpler tutorials, I'd love to have an one-button Redux tutorial it still can be plicated with multiple layers of ponents :(

I suspect the magic happens in TodoList.js as they're mapping over something there but still I have no idea where todos e from there, and what it has to do with Redux (there's no simple reducer/action/dispatch in that file).

Thanks for any help!

I've been trying hard to wrap my head around this concept but with no luck. The official React tutorial is really good but for me it's way too plex and just simply a little bit too hard.

I'm trying to understand Redux and so far I can create actions, reducers, I can dispatch an action and then see how the store state changes after dispatching it. I also managed to understand connect of react-redux and it works perfectly well and I'm able to trigger dispatches from any place in my app. So I think I almost got it figured out. Almost, because here's the elephant in the room - I dispatch the action, I see the Redux state change but HOW DO I CHANGE THE UI?

For example I have text object in my initial state with value Initial text and once a button is clicked I want to change the text to Clicked text and DISPLAY the text somewhere in the UI (let's say on the button).

How do I "access" the Redux state in React and how do I dynamicaly change it?

It seems to be very simple without React, e.g..: https://jsfiddle/loktar/v1kvcjbu/ - render function handles everything, I understand everything that happens here.

But on the other side "todo" from official React+Redux tutorial looks like this: https://redux.js/docs/basics/ExampleTodoList.html , it's so sophisticated I have no idea where to look.

The Add Todo button submits a form that dispatches dispatch(addTodo(input.value)) action. The action itself does nothing just increases the ID and passes the text to the store and the reducer just returns the new state. Then how the todo is being rendered on the page? Where? I'm lost at this point. Maybe there are simpler tutorials, I'd love to have an one-button Redux tutorial it still can be plicated with multiple layers of ponents :(

I suspect the magic happens in TodoList.js as they're mapping over something there but still I have no idea where todos e from there, and what it has to do with Redux (there's no simple reducer/action/dispatch in that file).

Thanks for any help!

Share edited Apr 28, 2019 at 6:36 Sagiv b.g 31k10 gold badges72 silver badges104 bronze badges asked Nov 25, 2017 at 15:37 WordpressorWordpressor 7,55326 gold badges75 silver badges115 bronze badges 1
  • 1 Look into mapStateToProps function, thats the last piece you are missing. It updates the props of your ponent from the redux state, thus triggering a rerender when your state changes. – xDreamCoding Commented Nov 25, 2017 at 15:53
Add a ment  | 

2 Answers 2

Reset to default 6

I think the confusion you have is that part of reducer position and selectors.

Let's look at it in a reverse order, from the UI back.

In the connected ponent containers/VisibleTodoList.js it gets the todos from the "state" (the global store object of redux) inside mapStateToProps, while passing it through the getVisibleTodos method.
Which can be called a selector, as it selects and returns only a portion of the data that it receives:

import { connect } from 'react-redux'
import { toggleTodo } from '../actions'
import TodoList from '../ponents/TodoList'

const getVisibleTodos = (todos, filter) => {
  switch (filter) {
    case 'SHOW_COMPLETED':
      return todos.filter(t => t.pleted)
    case 'SHOW_ACTIVE':
      return todos.filter(t => !t.pleted)
    case 'SHOW_ALL':
    default:
      return todos
  }
}

const mapStateToProps = state => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = dispatch => {
  return {
    onTodoClick: id => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

export default VisibleTodoList

The state (redux store) that passed to mapStateToProps came from the root reducer reducers/index.js and is actually a single reducer (object) that represent the bination of all other reducers via the bineReducers utility of redux:

  import { bineReducers } from 'redux'
  import todos from './todos'
  import visibilityFilter from './visibilityFilter'

  const todoApp = bineReducers({
    todos,
    visibilityFilter
  })

  export default todoApp   

As you can see, the todos reducer is there. so that's why inside the mapStateToProps we call it like this state.todos.

Here is the reducers/todos.js:

const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          pleted: false
        }
      ]
    case 'TOGGLE_TODO':
      return state.map(todo =>
        (todo.id === action.id) 
          ? {...todo, pleted: !todo.pleted}
          : todo
      )
    default:
      return state
  }
}

export default todos  

On each action of type 'ADD_TODO' it will return a new state with the new todo:

case 'ADD_TODO':
          return [
            ...state,
            {
              id: action.id,
              text: action.text,
              pleted: false
            }
          ]  

This the the action creator for it inside actions/index.js:

let nextTodoId = 0
export const addTodo = text => {
  return {
    type: 'ADD_TODO',
    id: nextTodoId++,
    text
  }
}

So here is the full flow of redux (i omitted the button that calls the action as i assume this is obvious part for you).
Well, almost a full flow, none of this could have happened without the Provider HOC that wraps the App and inject the store to it in index.js:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import todoApp from './reducers'
import App from './ponents/App'

let store = createStore(todoApp)

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Now when the redux state changes, a call to mapStateToProps is invoked that will return the new mapped props. connect will pass those new props and this will trigger a new render call (actually the entire react life cycle flow) to the connected ponent.
This way the UI will be re-rendered with the fresh new data from the store.

connect is typically used to connect react ponent and Redux state.connect is a higher order ponent. The ponent which are using connect function are wrapped inside it. The method signature is connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options]) mapStateToProps has access to redux state and mapDispathToProps has access to store.dispatch. All the props are merged and passed as props to underlying ponent. Redux has only single state of truth. store that is passed as a props to Provider ponents has a method called store.getState().

So , keep one thing in mind react ponents are data driven . Data derives UI. React ponents rerender only when state is changed or props have been modified. you make change in any of two , ponents goes through various life cycle methods.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744909225a4600445.html

相关推荐

  • javascript - How does Redux change UI in React? - Stack Overflow

    I've been trying hard to wrap my head around this concept but with no luck.The official React tut

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信