我是React和Redux的新手,之前我只使用过Angular。当我尝试使用Redux时,我遇到了学习React的第一个问题。我在(* Define the task including error handling. *)
let task = async {
let result = SyncApi.syncData(login.url, login.zone, login.user, login.pwd)
match result with
| Some msg ->
(* This may have to be posted back to the UI context.
Correct way depends on technology (Xamarin vs. WPF vs. MVC...) *)
showMsgError msg
| None -> ()
}
(* Fire and forget the async API call. *)
Async.Start(task)
(* Optimistically navigate away immediately,
while `task` may still be in progress. *)
rootPage.Navigation.PopToRootAsync(true) |> ignore
文件中定义了我的简单状态,动作,缩减器和存储:
index.tsx
修改了App组件,使其连接起来就像那样
export interface AppState {
count: number;
}
const INCREMENT = 'INCREMENT';
export class IncrementAction implements Action {
type = INCREMENT;
}
function opsReducer(state: AppState = {} as AppState, action: IncrementAction): AppState {
console.log("ops reducer", action);
switch (action.type) {
case INCREMENT:
return { ...state, count: state.count + 1 } as AppState;
default:
return state;
}
}
const rootReducer = combineReducers({
ops: opsReducer
});
const store = createStore(rootReducer);
ReactDOM.render(
<Provider store={store}>
<App appName="Test" />
</Provider>,
document.getElementById('root') as HTMLElement
);
index.tsx文件出错:
interface StateProps {
appName: string;
}
interface DispatchProps {
increment: () => void;
}
class App extends React.Component<StateProps & DispatchProps> {
render() {
return (
<div className="App">
<button onClick={this.props.increment}>CLICK ME {this.props.appName}</button>
</div>
);
}
}
function mapDispatchToProps(dispatch: Dispatch<AppState>) {
return {
increment: () => dispatch(new IncrementAction())
} as DispatchProps;
}
export default connect<StateProps, DispatchProps>(null, mapDispatchToProps)(App);
如何解决?如何使用TypeScript的硬打字来解决所有这些问题?当我最终修复它时,如何组织源代码?哪些东西应该移到分隔的文件?我喜欢基于功能的代码分离。如何使用React和Redux?
答案 0 :(得分:0)
我认为这里的关键问题是function opsReducer
。您说state
的类型是AppState
而初始值是空对象。而是{}
这样写:
function opsReducer(state: AppState = { count: 0 }, action: IncrementAction): AppState {
console.log("ops reducer", action);
switch (action.type) {
case INCREMENT:
return { ...state, count: state.count + 1 };
default:
return state;
}
}