Redux 中几个常用方法

react + redux

Posted by chanweiyan on July 11, 2020

Provider

容器组件

1
2
3
4
5
6
7
8
9
import { Provider } from 'react-redux';

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

mapStateToProps

1
2
3
4
5
6
7
// mapStateToProps
// 页面上的数据通过这个函数获取
const mapStateToProps = state => ({
  // 这是两个 reducers
  // state.todos, state.visibilityFilter
  todos: getVisibleTodos(state.todos, state.visibilityFilter)
});

mapDispatchToProps

1
2
3
4
5
// mapDispatchToProps
const mapDispatchToProps = dispatch => ({
  toggleTodo: id => dispatch(toggleTodo(id))
});

connect

1
2
3
4
5
6
7
8
import { connect } from 'react-redux';

// export
// 与 TodoList 组件进行关联
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList);

combineReducers

1
2
3
4
5
6
7
8
9
import { combineReducers } from 'redux';
import todos from './todos';
import visibilityFilter from './visibilityFilter';

// export
export default combineReducers({
  todos,
  visibilityFilter
});

源码

https://github.com/cwy007/todos_app