我有包含其他子组件的组件。两者都尝试从redux获得相同的状态。但是父组件成功完成此操作,因为子组件为null。代码是一样的。我在做什么错了?
父项
import './home.css';
import React from 'react';
import { connect } from 'react-redux';
import { Tabs, Tab, TabList, TabPanel } from 'react-tabs';
import { getSession } from 'app/shared/reducers/authentication';
import { createNewTab } from 'app/modules/home/code_tab.reducer';
import { Editor } from 'app/modules/home/editor';
export interface IHomeProp extends StateProps, DispatchProps {}
export class Home extends React.Component<IHomeProp> {
componentDidMount() {
this.props.getSession();
}
render() {
return (
<Editor />
);
}
}
const mapStateToProps = storeState => ({
codeTabs: storeState.codeTab.code_tabs
});
const mapDispatchToProps = { createNewTab };
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;
export default connect(
mapStateToProps,
mapDispatchToProps
)(Home);
子组件是:
import React from 'react';
import { connect } from 'react-redux';
import { Controlled as CodeMirror } from 'react-codemirror2';
import { createNewTab } from 'app/modules/home/code_tab.reducer';
import 'react-tabs/style/react-tabs.css';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
require('codemirror/mode/xml/xml');
export interface IEditorProp extends StateProps, DispatchProps {}
export class Editor extends React.Component<IEditorProp> {
render() {
console.log(this);
return <div>lala</div>;
}
}
const mapStateToProps = storeState => ({
codeTabs: storeState.codeTab.code_tabs
});
const mapDispatchToProps = {};
type StateProps = ReturnType<typeof mapStateToProps>;
type DispatchProps = typeof mapDispatchToProps;
export default connect(
mapStateToProps,
mapDispatchToProps
)(Editor);
因此,在第一种情况下,props中的codeTabs不为null,但在第二种情况下为null。另外我还注意到Editor中的codeTabs初始化发生在Home之前。
Reducer是:
import axios from 'axios';
import { REQUEST, SUCCESS, FAILURE } from 'app/shared/reducers/action-type.util';
import { ICodeTab } from '../../shared/model/code_tab.model';
export const ACTION_TYPES = {
ADD_NEW_TAB: 'code_tab/ADD_NEW_TAB',
GET_ALL: 'code_tab/GET_ALL'
};
const initialState = {
code_tabs: [] as ICodeTab[]
};
export type CodeTabState = Readonly<typeof initialState>;
// Reducer
export default (state: CodeTabState = initialState, action): CodeTabState => {
switch (action.type) {
case ACTION_TYPES.ADD_NEW_TAB:
const tab = new ICodeTab();
return {
...state,
code_tabs: [...state.code_tabs, tab]
};
case ACTION_TYPES.GET_ALL:
return {
...state
};
default:
return state;
}
};
const apiUrl = 'api/account';
export const createNewTab = () => ({
type: ACTION_TYPES.ADD_NEW_TAB
});
export const getAll = () => ({
type: ACTION_TYPES.GET_ALL
});