第一步:先下载redux的中间件
npm i react-redux react -D
第二步:在公共目录src下的index.js中进行路由与redux进行连接
import {HashRouter as Router} from 'react-router-dom';
import reportWebVitals from './reportWebVitals';
import App from './App';
//引入插件
import {Provider} from "react-redux"
import store from "./store"
ReactDOM.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
reportWebVitals();
第三步:在App.js中配置
import "./App.css";
import React, { Component } from "react";
import { renderRoutes } from "react-router-config";
import routes from "./routes";
import { Link } from "react-router-dom";
import "lib-flexible";
import {connect} from "react-redux"
class App extends Component {
constructor(...args) {
super(...args);
}
render() {
return (
<div className="home">
<div>
<Link className='item' to='/'>首页</Link>
</div>
<div>{renderRoutes(routes)}</div>
</div>
);
}
}
//进行连接
export default connect((props,state)=>Object.assign({},props,state),{})(App);
第四步:创建components文件件,在文件夹里常见一个index.js (路由中记得配置路由)
import {connect} from 'react-redux';
import {setName,setAge} from "../store/action";
import {Component} from 'react'
class pages extends Component{
FnName(){
const name= this.refs.name.value;
this.props.setName(name);
console.log(name);
}
fnSetAge(){
this.props.setAge(2);
}
render(){
return (<div>
当前年龄:{this.props.age}<br/>
<button onClick={this.fnSetAge.bind(this)}>点击</button><br/>
当前姓名:{this.props.name}<br/>
<input ref="name" type="text"/>
<button onClick={this.FnName.bind(this)}>点击</button><br/>
</div>)
}
}
export default connect((props,state)=>Object.assign({},props,state),{
setAge,setName
})(pages)
第五步:创建一个store文件夹,文件夹中创建action.js
export const SET_AGE='set_age';
export const SET_NAME='set_name';
export const setAge=function(n){
return {
type:SET_AGE,
n:n
}
}
export const setName=function(name){
return {
type:SET_NAME,
name:name
}
}
第六步:在store文件夹中在创建一个index.js
import { createStore } from "redux";
import { SET_AGE,SET_NAME} from "./action";
function user(state = { name: "blue", age: 18 }, action) {
switch (action.type) {
case SET_AGE:
return {
...state,
age: state.age + action.n,
};
case SET_NAME:
return {
...state,
name: action.name,
};
default:
return state;
}
}
export default createStore(user);
|