我想使用redux存储我整体的状态react应用程序,但是我遇到了一个特殊情况:
- 当组件需要本地状态并通过
componentDidUpdate
或componentDidMount
等生命周期方法修改时,如何使用 redux ?
包含由 isotope 排列的“卡片”的 react 组件示例布局库:
componentDidMount() {
let container = ReactDOM.findDOMNode(this);
if (! this.state.isotope) {
this.setState({ isotope: new Isotope(container, {itemSelector: '.grid-item', layoutMode: 'masonry'})});
}
}
componentDidUpdate(new_props, new_state) {
if (new_state.items_list != this.state.items_list) {
if (this.state.isotope) {
this.state.isotope.reloadItems();
this.state.isotope.layout();
this.state.isotope.arrange();
}
}
}
有没有办法删除此组件中的本地状态并改用 redux ?我不知道该怎么做
最佳答案
将您的 items_list 置于 redux 状态。您的 reducer 可能如下所示:
const initialState = {
items: []
};
export function myReducer(state = initialState, action) {
switch (action.type) {
case 'SET_ITEMS':
return Object.assign({}, state, {
items: action.items
});
}
return state;
}
或者更复杂一点的东西:
const initialState = {
items: []
};
export function myReducer(state = initialState, action) {
switch (action.type) {
case 'ADD_ITEM':
return Object.assign({}, state, {
items: [ ...state.items, action.item ]
});
case 'REMOVE_ITEM':
return Object.assign({}, state, {
items: [
...state.items.slice(0, action.index),
...state.items.slice(action.index + 1)
]
});
}
return state;
}
配置好 store 和 Provider 后(请参阅 Redux 文档),请像这样设置“智能组件”:
function mapStateToProps(state) {
return {
items: state.items
}
}
function mapDispatchToProps(dispatch) {
const actions = bindActionCreators(actionCreators, dispatch);
return {
addItem: actions.addItem,
removeItem: actions.removeItem
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Root);
现在您的项目和操作是您的根组件的 Prop 。如果您的项目位于较低阶组件中,只需将它们作为 props 沿树传递即可。
我希望这能给您一个总体思路。使用 Redux,您会发现您的 React 组件将使用更少的 state 和更多的 props。
还有一件事...
这可能是一个小问题,但我强烈建议您不要将同位素对象存储在组件状态上。 (无论您是否使用 Redux。)同位素对象并不是真正的状态,而是您的 View 。在 React 中,组件会更新以响应状态的变化。但您的 componentDidUpdate
则相反:它会更改状态以响应组件更新。
作为替代方案,只需将其存储在对象本身上。即
componentDidMount() {
const container = ReactDOM.findDOMNode(this);
this.isotope = new Isotope(container, {
itemSelector: '.grid-item',
layoutMode: 'masonry'
});
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.items !== this.props.items) {
this.isotope.reloadItems();
this.isotope.layout();
this.isotope.arrange();
}
}
(虽然通常我建议不要在 React 中使用此类实例变量,但像 Isotope 这样的 DOM 操作库是一个值得异常(exception)的异常(exception)。)
关于reactjs - React 组件的生命周期、状态和 redux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33905052/