1、加入依赖包
-
npm i redux -S
-
npm i react-redux -S
2.根元素加入Provider,创建store
index.js里
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
// 路由
import { HashRouter as Router } from 'react-router-dom'
// redux
import { Provider } from "react-redux"
import store from "./store"
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();
根据上面Index.js里 主要加入的是
// redux
import { Provider } from "react-redux"
import store from "./store"
<Provider store={store}>
<App />
</Provider>,
3.新建store文件夹
在store下index.js里
import { createStore } from "redux"
import { SET_AGE, SET_NAME } from "./action"
function user(state = { name: "Jack", age: 18 }, action) {
switch (action.type) {
case SET_AGE:
return {
...state,
age: state.age + action.n,
}
case SET_NAME:
return {
...state,
name: action.m
}
default:
return state;
}
}
export default createStore(user)
在store下actions.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 (m) {
return {
type: SET_NAME,
m: m
}
}
4.App.js里 加入
//引入
import { connect } from "react-redux"
最后把导出改了
// export default App;
export default connect((props, state) => Object.assign({}, props, state), {})(App)
5.页面中的使用
import React, { Component } from "react"
import { connect } from "react-redux";
import { setAge } from "./../store/action"
import { setName } from "./../store/action"
class About extends Component {
FnSetAge() {
this.props.setAge(2)
}
FnName() {
this.props.setName(this.refs.valueName.value)
}
render() {
return (<div>
当前年龄:{this.props.age}
<button onClick={this.FnSetAge.bind(this)}>点击</button><br />
<input ref="valueName" type="text" />
<button onClick={this.FnName.bind(this)}>dianji</button><br />
姓名:{this.props.name}
</div >)
}
}
export default connect((props, state) => Object.assign({}, props, state), {
setAge, setName
})(About)