将组件中的初始状态设置为Redux存储

时间:2018-02-02 14:03:51

标签: reactjs typescript redux react-redux

我正在使用来自VS的模板项目(React + Redux + TS),我不确切知道如何设置组件状态,因为当我在构造函数中执行此操作时,它会省略它。

组件看起来像有两个状态(?):own和store。我不明白这种机制......

class Nodes extends React.Component<{ handleClick: () => void, nodes: NodeProps[], force: any}, NodeStore.NodeState>{

    constructor(props: any){
        super(props);

        this.state = {name: "test"}; //change 'in' component state
    }

    render(){
        const nodes = this.props.nodes.map((node: NodeProps, index: number) => {
            return <Node key={index} node={node} onClick={this.handleClick} />;
            });

        return (
            <g className="nodes">
            {nodes}
            TestName: {this.state.name} // thats always "test", but after click should be "testaddedstring" 
            </g>
        );
    }

    private handleClick =() => {
        this.props.handleClick();
        alert("clicked!");
    }
}

const mapStateToProps = (state: ApplicationState) => {
    return {
        name: state.node.name // state from store not from component
    }
};

const mapDispatchToProps = {
    handleClick: NodeStore.actionCreators.changeName
};

export default connect<any, typeof NodeStore.actionCreators, any>(
    mapStateToProps,
    mapDispatchToProps
)(Nodes);

这是带有商店定义的index.ts文件:

export interface ApplicationState {

    node: Node.NodeState; 
}

export const reducers = {
    node: Node.reducer
};

export interface AppThunkAction<TAction> {
    (dispatch: (action: TAction) => void, getState: () => ApplicationState): void;
}

和动作减速器:

export interface NodeState {
    name: string;
}

interface ChangeNameAction {type: 'CHANGE_NAME'}

export const actionCreators = {
    changeName: () => <ChangeNameAction>{ type: 'CHANGE_NAME' }
}

export const reducer: Reducer<NodeState> = (state: NodeState, action: ChangeNameAction) => {
    if (action.type === 'CHANGE_NAME'){
        return { name: state.name + "addedstring"};
    }

    return state || {name: "default name"};
};

错过了什么?

1 个答案:

答案 0 :(得分:0)

mapStateToProps()将道具传递到您的组件而不是状态。

因此,当您致电this.props.handleClick()时,name(现在等于“testaddedstring”)将被传递到Nodes道具,并且可以在this.props.name组件内部进行访问。但是,this.state.name不受影响。如果您想在this.state.name内更新componentWillReceiveProps(),则需要更新interface Props { force: any; handleClick: () => void; name: string; nodes: NodeProps[]; } class Nodes extends React.Component<Props, NodeStore.NodeState> { componentWillReceiveProps(nextProps: Props, nextState: NodeStore.NodeState): void { this.setState({ name: nextProps.name }); } ... } 。像这样:

this.props.name

或者您在this.state.name中使用render()代替name。正如您现在所拥有的那样,没有必要将entryBox[i * ROW_SZ + j]->set_size_request(40); 置于组件状态,因为您没有在组件内部进行编辑。所以你可以完全删除你的构造函数。