Redux简单的一个小实例
import React from 'react';
import { createStore } from 'redux';
const initState = [
{
id: 1,
text: 'test1'
}
];
const reducer = function(state = initState, action) {
switch(action.type) {
case 'ADD_TODO':
return [
...state,
action.payload
]
default:
return state;
}
}
const store = createStore(reducer);
class Index extends React.Component {
constructor() {
super();
this.state = {
todos: [],
val: ''
}
}
temp = null;
componentDidMount() {
this.setState({
todos: store.getState()
});
this.temp = store.subscribe(() => {
this.setState({
todos: store.getState()
});
});
}
componentWillUnmount() {
this.temp();
}
handleChangeVal = (e) => {
this.setState({
val: e.target.value
});
}
handleEnter = (e) => {
if(e.keyCode === 13) {
const val = e.target.value;
const action = {
type: 'ADD_TODO',
payload: {
id: val,
text: val
}
};
store.dispatch(action);
}
}
render() {
const { val } = this.state;
return (
<div>
<h1>Redux的使用实例</h1>
<input value={val} onChange={this.handleChangeVal} onKeyUp={this.handleEnter} />
<ul>
{
this.state.todos.map((item, index) => {
return (
<li key={index}>{item.text}</li>
)
})
}
</ul>
</div>
)
}
}
export default Index;
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。