React组件生命周期,状态和redux

mgu*_*arr 8 reactjs redux isotope

我想使用redux来存储我的整个反应应用程序的状态,但是我遇到了一个特定的情况:

  • 如何处理时Redux的组件需要一个本地状态,通过生命周期方法,如修改componentDidUpdatecomponentDidMount

包含由同位素布局库排列的"卡片"的反应组件示例:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法删除此组件中的本地状态并使用redux?我看不出怎么做

Dav*_*lsh 16

将items_list置于redux状态.您的减速器可能如下所示:

const initialState = {
    items: []
};

export function myReducer(state = initialState, action) {
    switch (action.type) {
        case 'SET_ITEMS':
            return Object.assign({}, state, {
                items: action.items
            });
    }
    return state;
}
Run Code Online (Sandbox Code Playgroud)

或者更复杂的东西:

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;
}
Run Code Online (Sandbox Code Playgroud)

配置商店和提供商后(请参阅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);
Run Code Online (Sandbox Code Playgroud)

现在,您的项目和操作是Root组件的道具.如果您的商品位于较低级别的组件中,只需将它们作为道具传递到树下.

我希望能给你一般的想法.使用Redux,你会发现你的React组件将使用更少的状态并且支持更多.

还有一件事...

这可能是一个小问题,但我建议您不要将同位素对象存储在组件状态中.(无论你是否使用Redux.)同位素对象实际上不是一个状态,这是你的观点.在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

(虽然通常我建议不要在React中使用这些实例变量,但像Isotope这样的DOM操作库是一个值得例外的例外.)