关于这一个的很多主题,但它们几乎都是关于状态被某种程度上变异的,我认为这不是我的情况。所以我有一个在两个组件之间共享的状态。
export interface ImageStoreState {
readonly name : string;
}
减速器,
export function imageActionReducer(state: ImageStoreState, action:ImageActions): ImageStoreState {
// Set up initial states
if (state === undefined)
{
state = {
name: ""
}
}
console.log("original state", state);
switch (action.type) {
case getType(imageActions.saveImageMeta):
console.log("SaveImageMeta Reducer.");
return { ...state,
name: action.payload.name
};
}
console.error("No matching reducer.");
return state;
}
容器,
export function mapStateToProps(state: ImageStoreState) : IAddImageControlProps {
const { name } = state;
console.log("Add image control container, mapStateToProps", state);
return {
imageChosen: name
}
}
export function mapDispatchToProps() {
return {
//
};
}
export const AddImageControlContainer
= connect<IAddImageControlProps, {}, IAddImageControlProps, ImageStoreState>(mapStateToProps, mapDispatchToProps)(AddImageControl);
演示组件
export interface IAddImageControlProps {
imageChosen?: string;
// onImageAdded?: (im: ImageFile) => any;
}
export class AddImageControl extends React.Component<IAddImageControlProps, {}> {
constructor(props : IAddImageControlProps) {
super(props);
}
public componentWillReceiveProps(nextProps: IAddImageControlProps) {
console.log('componentWillReceiveProps', nextProps);
}
public render() : JSX.Element {
const { imageChosen } = this.props;
let isEnabled = false;
if (imageChosen !== undefined)
{
isEnabled = true;
console.log(imageChosen);
}
console.log("Should enbale:" + isEnabled);
return (
<section>
<Button type="button" color="success" disabled={!isEnabled}>Add it!</Button>
</section>
);
}
}
我正在使用redux dev-tools所以我可以看到状态在变化,
但行
console.log('componentWillReceiveProps', nextProps);
console.log("Should enbale:" + isEnabled);
永远不要被召唤!
提前谢谢大家!我已经想好了几天了。