下载依赖
npm i react-redux react -D
在公共目录src下的index.js中进行路由与redux进行连接
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {HashRouter as Router} from 'react-router-dom';
import { Provider } from 'react-redux'; /* redux使用 */
import store from './store'; /* redux使用 */
import 'lib-flexible';
ReactDOM.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
app.tsx中
import './App.css';
import { Link } from 'react-router-dom'
import { renderRoutes, RouteConfig } from 'react-router-config';
import {connect} from "react-redux"
import routes from './routers/router'
import { Component } from "react";
interface Props{
}
interface State{
}
class App extends Component<Props,State> {
constructor(props:Props) {
super(props);
this.state={}
}
render() {
return (
<div className="home">
<div>
<Link className='home' to='/'>首页</Link> |
<Link className='about' to='/about'>关于</Link> |
<Link className='comp' to='/comp'>Redux+ts</Link>
</div>
<div>{renderRoutes(routes as RouteConfig[])}</div>
</div>
);
}
}
//进行连接
export default connect((props,state)=>Object.assign({},props,state),{})(App);
在src里创建store文件夹,里面有两个文件action.tsx 和index.tsx
action.tsx中
export const SET_AGE='set_age';
export const setAge=function(n:number){
return {
type:SET_AGE,
n:n
}
}
index.tsx中
import { createStore } from "redux";
import { SET_AGE} from "./action";
interface Action{
type:string,
n:number,
}
interface State{
age:number
}
function user(state = { age: 18 }, action: Action):State {
switch (action.type) {
case SET_AGE:
return {
...state,
age: state.age + action.n,
};
default:
return state;
}
}
export default createStore(user);
再创建一个组件
/* 类组件使用redux */
import { Component } from 'react'
import { connect } from 'react-redux'
import {setAge} from "../../store/action";
interface Props{
setAge:Function,
age:number
}
interface State{
}
class Comp extends Component<Props,State>{
constructor(props:Props) {
super(props);
this.state={}
}
fnSetAge(){
this.props.setAge(2);
}
render(){
return (<div>
当前年龄:{this.props.age}<br/>
<button onClick={this.fnSetAge.bind(this)}>点击</button><br/>
</div>)
}
}
export default connect((props,state)=>Object.assign({},props,state),{
setAge
})(Comp)