首页 > 其他 > 详细

[Redux] Generating Containers with connect() from React Redux (VisibleTodoList)

时间:2016-02-09 08:03:36      阅读:188      评论:0      收藏:0      [点我收藏+]

Learn how to use the that comes with React Redux instead of the hand-rolled implementation from the previous lesson.

 

Code to be refactored:

class VisibleTodoList extends Component {
  componentDidMount() {
    const { store } = this.context;
    this.unsubscribe = store.subscribe(() =>
      this.forceUpdate()
    );
  }
  
  componentWillUnmount() {
    this.unsubscribe();
  }
  
  render() {
    const props = this.props;
    const { store } = this.context;
    const state = store.getState();
    
    return (
      <TodoList
        todos={
          getVisibleTodos(
            state.todos,
            state.visibilityFilter
          )
        }
        onTodoClick={id =>
          store.dispatch({
            type: ‘TOGGLE_TODO‘,
            id
          })            
        }
      />
    );
  }
}

VisibleTodoList.contextTypes = {
  store: React.PropTypes.object
};

In the code, we handle the ‘context‘, subscribe state and unsubscribe. Also we need to always remember write ‘contextTypes‘. There are lots of things todo.

Actually we can use ‘ReactRedux‘ libaray to simpy our life:

 

VisibleTodoList:

So get the todos and write into mapStateToProps function:

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

 

then get onTodoClick dispatch function to the mapDispatchToProps function:

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch({
        type: ‘TOGGLE_TODO‘,
        id
      });
    }
  };
};

 

then we can use ‘connect()()‘ function to connect state, dispatch action and Render component together:

const { connect } = ReactRedux;
const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList);

 

-------------------------

code:

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

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch({
        type: ‘TOGGLE_TODO‘,
        id
      });
    }
  };
};

const { connect } = ReactRedux;
const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList);

 

[Redux] Generating Containers with connect() from React Redux (VisibleTodoList)

原文:http://www.cnblogs.com/Answer1215/p/5185401.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!