以下为使用Redux步骤
1.创建数据存储仓库(store)
import {createStore} from 'redux'
//创建数据公共存储仓库
export const store = createStore();
2.创建Reducer(记录本)
//reducer 笔记本
const defaultState = {
inputValue: '123',
list:[{'name':'zhangsan', 'age':'20'},{'name':'lisi', 'age':'30'}]
};
//state: 笔记本里面存储的数据 (也可以认为是仓库里面存储的数据)
export default (state = defaultState,action) =>{
return state;
}
这里defaultState初始化一些数据,赋值给state
3.将store和reducer关联起来
import reducer from './TodoListReducer'
const store = createStore(reducer);
4.Component中通过 store.getState() 获取仓库中的数据
class TodoListPage extends Component {
constructor(props) {
super(props);
console.log("store state: "+ (JSON.stringify(store.getState())));
this.state = store.getState();
console.log("this.state state: "+ (JSON.stringify(this.state)));
}
}
5.Component将拿到的数据做展示
render() {
return (
<View style={styles.container}>
<TextInput style = {{borderColor:'red', borderWidth:1,width:300}} onChangeText= { (inputText) => {
console.log('TextInput onChangeText '+ inputText)
this.handleInputChange(inputText);
}}
value={this.state.inputValue}
/>
<Text >输入的值 {this.state.inputValue}</Text>
<Button title= '确认' onPress={this.handleSubmit}></Button>
<FlatList
data={
this.state.list
}
renderItem={
({item}) => <Text style ={styles.itemText}>{item}</Text>
}
keyExtractor={item => item}
/>
</View>
);
}
流程: Component(借书的人)-> action:借书说的话 -> store图书馆的管理员 (没办法知道所有书的资料的)-> Reducer(书的记录本)
借书的人(component)说我要借一本书(发出一个action) ->被store(管理员)听到了 -> 管理员需要去 reducer查询书的信息,reducer把书籍信息返回给store, store修改数据,component就可以获得数据了
当input有修改时,触发handleInputChange(), 需要发出一个action,action中定义type(代表需要干什么事情),value代表传递的值
component如何感知store的变化呢? 需要在contructor监听state的改变,监听到该表后调用setState触发页面刷新
class TodoListPage extends Component {
constructor(props) {
super(props);
console.log("store state: "+ (JSON.stringify(store.getState())));
this.state = store.getState();
//当store变化的时候执行handleStoreChange
store.subscribe(this.handleStoreChange)
}
//当感知仓库数据改变了,修改state,触发界面刷新
handleStoreChange(){
this.setState(store.getState());
}
网友评论