App.js
import React from 'react'; // 生成虚拟DOM
import store from "./store/store";
import {addAction, subAction} from "./store/action";
import Son from "./Components/Son";
import Son2 from "./Components/Son2";
import './App.css'
class App extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
count: store.getState().count // 获取数据
}
}
componentDidMount() {
store.subscribe(()=>{
this.setState({
count: store.getState().count
})
})
}
componentWillUnmount() {
store.unsubscribe()
}
render(){
return (
<div>
<p className='title'>React的子组件使用Redux</p>
<p>{this.state.count}</p>
<Son/>
<Son2/>
</div>
)
}
}
export default App; // 暴露给外界
Son.js
import React from 'react'; // 生成虚拟DOM
import store from "../store/store";
import {addAction, subAction} from "../store/action";
class Son extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
count: store.getState().count // 获取数据
}
}
componentDidMount() {
store.subscribe(()=>{
this.setState({
count: store.getState().count
})
})
}
componentWillUnmount() {
store.unsubscribe()
}
render(){
return (
<div>
<p>{this.state.count}</p>
<button onClick={()=>{this.btnClick()}}>递增</button>
</div>
)
}
btnClick(){
store.dispatch(addAction(1))
}
}
export default Son; // 暴露给外界
Son2.js
import React from 'react'; // 生成虚拟DOM
import store from "../store/store";
import {addAction, subAction} from "../store/action";
class Son2 extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
count: store.getState().count // 获取数据
}
}
componentDidMount() {
store.subscribe(()=>{
this.setState({
count: store.getState().count
})
})
}
componentWillUnmount() {
store.unsubscribe()
}
render(){
return (
<div>
<p>{this.state.count}</p>
<button onClick={()=>{this.btnClick()}}>递减</button>
</div>
)
}
btnClick(){
store.dispatch(subAction(1))
}
}
export default Son2; // 暴露给外界

这个示例展示了如何在React应用中使用Redux来管理状态。`App.js`作为主要组件,从`store`订阅状态变化,并显示在页面上。`Son.js`和`Son2.js`作为子组件,同样订阅了`store`,并各自有增加和减少计数的按钮,通过调用`addAction`和`subAction`更新全局状态。
8074

被折叠的 条评论
为什么被折叠?



