create-react-app my-react-redux-app
cd my-react-redux-app
删除src文件夹下所有文件,新建./src/index.js
文件,执行npm start
启动项目
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
//1新建store
//通过reducer的简历
//根据state和action生成新的state
function counter(state=0, action) {
switch (action.type) {
case '加机关枪':{
return state+1;
}
case '减机关枪': {
return state-1;
}
default: {
return 10;
}
}
}
const store = createStore(counter);
let init = store.getState();
console.log(init);
// 派发事件 传递action
//当定义了store后,store.dispatch在store.subscribe之后,即最后触发更新
function lisenter() {
let current = store.getState();
console.log(`现在有机关枪${current}把`);
}
store.subscribe(lisenter);
store.dispatch({type: '加机关枪'});
store.dispatch({type: '加机关枪'});
store.dispatch({type: '减机关枪'});
//jsx---------------------------------------------------------------------------
console.log('现在开始渲染组件');
class App extends React.Component {//类必须先声明再使用
render() {
console.log('渲染中...');
return (
<div>
<h1>hello</h1>
<h2>hello</h2>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
console.log('现在结束渲染组件');
//jsx---------------------------------------------------------------------------
访问localhost:3000并打开控制台,会得到
10
现在有机关枪11把
现在有机关枪12把
现在有机关枪11把
现在开始渲染组件
渲染中...
现在结束渲染组件
这就是基本的redux使用,现在redux是单独使用的