javascript - 在 React Native 组件中获取 Redux 存储数据
问题描述
我开始使用 Redux 和 React Native,我在尝试获取组件中存储的数据时遇到了很多困难,这有什么特别之处,只是一个按钮来改变商店,另一个按钮来打印它,因为我还是个新生儿
// TestComponent.js
<Button onPress={ () => { this.props.todoAdd("cafee") } }>
<Text>Covfefe</Text>
</Button>
<Button onPress={ () => { console.log(this.state) } }>
<Text>Todo alc</Text>
</Button>
const mapStateToProps = (state, props) => {
return {
todos: state,
};
};
const mapDispatchToProps = (dispatch) => {
return {
todoAdd: (name) => dispatch({type: 'TODO_ADD', todo: { id: '0', name, completed: false }}),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(TestComponent)
添加按钮有效,我在 App.js 中注册了一个订阅,因此我可以看到商店中的每个更新,我很高兴至少有一件事情有效但我很困惑,我想获取存储的数据但我无法让它工作!
我读到 mapStateToProps 实际上侦听更改和触发器,使用您编写的组件需要的数据更新组件的道具,我写了 props.todos = state 所以整个状态应该在 this.props.todos 中,不它?我不知道,但是当我打印组件道具时,我得到一个空对象。
我的商店还有其他配置文件:
// store/index.js
import {createStore} from 'redux';
import Reducers from './reducers'
export default configureStore = () => {
let store = createStore(Reducers, [])
return store
}
// store/reducers.js
export default function reducer(state, action) {
switch(action.type) {
case 'TODO_ADD' : {
return applyAddTodo(state, action);
}
case 'TODO_TOGGLE' : {
return applyToggleTodo(state, action);
}
default : return state;
}
}
function applyAddTodo(state, action) {
return state.concat(action.todo);
}
function applyToggleTodo(state, action) {
return state.map(todo =>
todo.id === action.todo.id
? Object.assign({}, todo, { completed: !todo.completed })
: todo
);
}
// App.js
import {Provider} from 'react-redux';
import configureStore from './store/index'
let store = configureStore()
const unsubscribe = store.subscribe(() => {
console.log('store update, current state:');
console.log(store.getState());
});
const MainNavigator = createStackNavigator({
Home: {screen: TestComponent},
});
const Root = createAppContainer(MainNavigator);
export default class App extends Component {
render() {
return (
<Provider store={store}>
<Root />
</Provider>
);
}
}
我只是想知道如何获取数据来打印它,我刚开始学习 redux,所以非常欢迎任何提示,无论如何感谢您阅读我。
解决方案
尝试console.log(this.props.todos)
由于您将整个 redux 存储状态映射到todos
您应该在以下位置找到它的对象this.props.todos
推荐阅读
- java - 使用嵌套的静态类模拟接口
- laravel - 是否可以使用 laravel 中的时间戳将 Jalali 日期存储在 created_at 和 updated_at 字段中?
- java - Github Java Maven Actions 持续集成 POM 是在引用自己
- memory - 给出 32 位主存中的字数
- flutter - 无法使用 Flutter 中的对象列表创建 DropdownButton
- python-3.x - 在线结果搜索应用程序的第一个 html 页面应呈现表单,第二个页面将显示数据。帮助应用?
- uml - 用例图关系和应用程序工作流程
- ios - 如何在图像成功上传到服务器时显示蓝色勾号,以及正在上传的图像的加载时钟
- flutter - 卡片设计
- android-architecture-components - 嵌套导航图中的工具栏后退按钮