我正在学习redux,我想在react -redux中包括打字稿。我有一个简单而基本的应用程序,如下所示。
如何在上面添加打字稿。我尝试查看各种示例,但是我迷失在中间。我尝试查看How to type Redux actions and Redux reducers in TypeScript?。我不能适应它。最好在一个非常简单且基本的示例中使用它,因为我是Typescript和Redux的新手。
import React, { Component } from 'react';
import Main from './components/Main';
import {BrowserRouter} from 'react-router-dom';
import {createStore, combineReducers} from 'redux';
const initialState={
items:[],
filter:'none',
discount:0
}
const itemReducer =(state=initialState, action) =>{
switch(action.type)
{
case 'add_item':
return Object.assign({},state, {items:[...state.items, action.product]})
case 'filter':
return Object.assign({}, state, {filter:action.filter } )
case 'discount':
return Object.assign({}, state, {discount:action.discount})
case 'delete_item':
return Object.assign({},state, {items:[...state.items.slice(0,action.index), ...state.items.slice(action.index+1)]})
default:
return state;
}
}
const addItem = (name, price) =>{
return{
type:'add_item',
product :{
name:name,
price:price
}
}
}
const deleteItem =(index)=>{
return{
type: 'delete_item',
index: index
}
}
const setFilter =(filterBy)=>{
return{
type:'filter',
filter: filterBy
}
}
const setDiscount =(discount)=>{
return{
type:'discount',
discount: discount
}
}
var store = createStore(itemReducer);
store.dispatch(addItem("apple", 100));
store.dispatch(setFilter("name"));
store.dispatch(setDiscount("20"));
store.dispatch(addItem("oranges", 200));
store.dispatch(addItem("pineapples", 500));
store.dispatch(deleteItem(2));
console.log(store.getState())
class App extends Component {
render() {
return (
<BrowserRouter>
<Main />
</BrowserRouter>
);
}
}
export default App;