VanillaJS其实是原生JS
Redux官方示例:
https://www.redux.org.cn/docs/introduction/Examples.html
重写示例
Redux版
http://js.jirengu.com/gikoxocesa/2/edit?html,output
React + Redux版
安装redux
yarn add redux
# 或者
npm install --save-dev redux
npm和yarn不要混用,优先用yarn
代码连接
优点:Ract不会每次都整体更新,通过DOM diff更新有变化的地方
缺点:store要一层一层往下传
React-Redux版
官方文档:https://react-redux.js.org/introduction/quick-start
安装React-Redux
yarn add react-redux
用Provider包裹App
import {Provider} from 'react-redux'
function changeState(state, action){
if(state === undefined){
return {n: 0}
}else{
if(action.type === 'add'){
return {n: state.n + action.payload}
} else {
return state
}
}
}
const store = createStore(changeState)
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
在App组件中引入connect
import {connect} from 'react-redux'
function App(props) {
return (
<div className="App">
点击了<span id="value">{props.n}</span>次
<div>
<button id="add" onClick={()=>{props.add1()}}>+1</button>
<button id="add2" onClick={()=>{props.add2()}}>+2</button>
<button id="addIfOdd" onClick={()=>{props.add3()}}>如果是单数就+1</button>
<button id="addAfter2Sec" onClick={()=>{props.add4()}}>2s后+1</button>
</div>
</div>
);
}
function mapStateToProps(state){
return {
n: state.n
}
}
function mapDispatchToProps(dispatch) {
return {
add1: () => {dispatch({type:'add', payload: 1})}
}
}
export default connect(mapStateToProps,actionCreator)(App);
上一篇:Context
下一篇:组件通信之Eventhub