Adding Redux to an Existing React Application

I worked on a React application and got to the point where I need Redux to handle some of its aspects.

After reading a bunch of tutorials, I'm pretty obsessed with how to make my smart components dumb and move functions to my actions and gears.

So, for example, one aspect of the application is more of a to-do list style.

One of my classes starts as follows:

export default class ItemList extends React.Component {
  constructor() {
    super();
    this.state = { items: [],
                   completed: [],
                  };
    this.addItem = this.addItem.bind(this);
    this.completeItem = this.completeItem.bind(this);
    this.deleteItem = this.deleteItem.bind(this);
  }

  addItem(e) {
    var i = this.state.items;
    i.push({
      text: this._inputElement.value,
      paused: false,
      key: Date.now()
    });
    this.setState({ items: i });
    e.preventDefault();
    this._inputElement.value = '';
    this._inputElement.focus();
  }

  completeItem(e) {
    this.deleteItem(e);
    var c = this.state.completed;
    c.push({
      text: e.target.parentNode.parentNode.getElementsByClassName('item-name')[0].innerHTML,
      paused: false,
      key: Date.now()
    });
    this.setState({ completed: c });
  }

  deleteItem(e) {
    var i = this.state.items;
    var result = i.filter(function(obj) {
        return obj.text !== e.target.parentNode.parentNode.getElementsByClassName('item-name')[0].innerHTML;
    });
    this.setState({ items: result });
  }

  // ... more irrelevant code here ...

  // there a function called createTasks that renders individual items

  render() {
    var listItems = this.state.items.map(this.createTasks);

    return <div className="item-list">
      <form className="form" onSubmit={this.addItem}>
        <input ref={(a) => this._inputElement = a}
               placeholder="Add new item"
               autoFocus />
        <button type="submit"></button>
      </form>

      {listItems}
    </div>;
  }
}

So, as you can see, this is very logical-heavy. I started adding Redux by adding <Provider>to my index file and made a basic reducers file, which is still pretty empty:

import { combineReducers } from 'redux';

const itemList = (state = {}, action) => {

};

// ... other irrelevant reducers

const rootReducer = combineReducers({
  itemList,
  // ...
});

export default rootReducer;

... and I made an action file that does not yet have much in it.

I'm struggling to figure out:

  • , , - JSON, , JSON, ?
  • , ? , , , ?
+6
1

, , .

, , .

  • .
  • .
  • (, ) .

  • .
  • /html/css .

- , , , .

, , : -

  • (, ) .
  • .
  • apis
  • .
  • mapStateToProps, , .

todo

TodoListContainer.js

class TodoListContainer extends Component {

  componentWillMount () {
    // fire you action action
  }


  render () {
    return (
      <Todos todos=={this.props.todos} />
    )
  }
}


function mapStateToProps(state) {
  const {todos} = state;
  return {
    todos;
  }
}

export default connect(mapStateToProps)(TodoListContainer)

TodoList.js

class TodoList extends Component {

  renderTodos() {
    return this.props.todos.map((todo)=>{
      return <Todo todo={todo} key={todo.id} />
    })
  }

  render () {
    return () {
      if (this.props.todos.length === 0) {
        return <div>No todos</div>
      }
      return (
        <div>
          {this.renderTodos()}
        </div>
      )
    }
  }
}

export default class TodoList

Todo.js

class Todo extends Component {

  render () {
    return (
      <div>
        <span>{this.props.todo.id}</span>
        <span>{this.props.todo.name}</span>
      </div>
    )
  }
}

export default function todos(state={},action) {
  switch (action.type) {
    case 'RECEIVE_TODOS':
       return Object.assign(state,action.todos);
  }
}

function fetchTodos() {
  return(dispatch) => {
      axios.get({
    //api details
    })
    .then((res)=>{
      dispatch(receiveTodos(res.todos))
    })
    .catch((err)=>{
      console.warn(err)
    })
  }
}

function receiveTodos(todos) {
  return {
    type: 'RECEIVE_TODOS',
    todos
  }
}

, redux, , , api, . redux thunk, .

, todos. , deleteTodo, addTodo, modifyTodo, .

  • DeleteTodo - TodoListContainer.
  • AddingTodo - TodoListContainer.
  • (/) - TodoListContainer.
  • ModifyingTodo - TodoContainer.

, , ,

P.S: " ", , .

+16

Source: https://habr.com/ru/post/1016514/


All Articles