react+ts配置redux

下载依赖

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(
   
  
    
  
  ,
  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 {
  constructor(props:Props) {
    super(props);
    this.state={}
  }
  render() {
    return (
      
首页 |  关于 |  Redux+ts
{renderRoutes(routes as RouteConfig[])}
); } } //进行连接 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{
  constructor(props:Props) {
    super(props);
    this.state={}
  }
 
    fnSetAge(){
      this.props.setAge(2);
    }
 
    render(){
      return (
当前年龄:{this.props.age}

) } } export default connect((props,state)=>Object.assign({},props,state),{ setAge })(Comp)

你可能感兴趣的:(react.js,javascript,前端)