【发布时间】:2021-03-26 00:14:44
【问题描述】:
我正在尝试将this 样板用于我的反应打字稿项目。我无法配置正确的操作类型。使用 JavaScript 很容易。但我是 TypeScript 的新手。我想知道为什么我的代码不起作用。还请提出解决此问题的最佳方法。
Dashboard.tsx
interface IAction{
type: string,
payload: any,
}
interface IProps {
// dashboard: DashboardState;
dashboard: any;
// Actions
changeUserName: IAction;
}
interface IState {}
class Dashboard extends React.Component<IProps, IState> {
componentDidMount(){
console.log("____FOCUS____");
console.log(this.props);
this.props.changeUserName("NewName");
console.log("____FOCUS____");
// this.props.changeUserName('New Name');
}
render() {
return (
<>
<Helmet>
<title>Dashboard</title>
<meta name="description" content="Description of Dashboard" />
</Helmet>
<DashboardComponent username={'somevalue'} />
{/* <Div>{t('')}</Div> */}
</>
);
}
}
const mapStateToProps = (state: any, ownProps: any) => ({
dashbaord: selectDashboard(state),
});
const mapDispatchToProps = (dispatch: any, ownProps: any) => ({
...bindActionCreators({
...actions,
}, dispatch),
});
const withConnect = connect(mapStateToProps, mapDispatchToProps);
const withReducer = injectReducer({key: sliceKey, reducer: dashboardReducer});
const withSaga = injectSaga({key: sliceKey, saga: dashboardSaga});
export default compose(
withReducer,
withConnect,
withSaga,
)(Dashboard);
类型
我正在创建的类型也与文档中的一样。
/* --- STATE --- */
export interface DashboardState {
username: string;
}
export type ContainerState = DashboardState;
切片
这是我正在创建的切片。如文档中所述。
export const initialState: ContainerState = {
username: 'Initial Username',
};
const dashboardSlice = createSlice({
name: 'dashboard',
initialState,
reducers: {
changeUserName(state, action: PayloadAction<string>) {
state.username = action.payload;
},
},
});
export const { actions, reducer, name: sliceKey } = dashboardSlice;
【问题讨论】:
-
您能准确分享一下什么不起作用吗?您收到什么样的错误信息?此外,您的
mapStateToProps()方法中有错字(“dashbaord”) -
其实我的代码也是无效的。它正在工作,但我没有有效的接口。如果可以的话,请告诉我。
-
此表达式不可调用。 “IAction”类型没有调用签名。 TS2349 this.props.changeUserName("NewName");
-
我没有用于 reducer 切片操作的适当接口实现。你能举个例子吗?
-
我建议查看 this guide 的 redux reducers
标签: reactjs typescript react-redux redux-saga stateful