您可以通过终极版做到这一点,仍然避免更新所有组件。是的,你可以调整你的当前组件是否应该更新。这里的示例代码
class VisibleTodos extends Component{
componentDidMount(){
this.unsubscribe = store.subscribe(() => {
this.forceUpdate();
});
}
componentWillUnmount() {
this.unsubscribe();
}
render(){
const state = store.getState();
return(
<TodoList
todos = {getVisibleTodos(
state.todos,
state.visibilityFilter
)}
onTodoClick = {id => {
store.dispatch({
type: 'TOGGLE_TODO',
id
})
}}
>
</TodoList>
)
}
}
与反应,终极版库同样的事情会做的
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);
所以,想象一下有与此类似,并在前者的情况下其他几个组件,调用this.forceUpdate()
和this.unsubscribe()
会是多余的。因此,它使我们免于手动工作。
通过react-redux,您可以使用'connect'功能将任何组件连接到应用商店。如果没有连接,你必须手动完成。而且,一般来说,任何图书馆的目的都是为了减少手工工作量。 –
由于您在Redux中创建的任何订阅都会在每次状态更改时被调用,无论您是否需要在该状态片上进行操作。 'react-redux'允许我们指定某些组件应该订阅的商店的哪些部分,因此我们只需“订阅”我们想要的更改。 – lux