首页 > 解决方案 > 在 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,所以非常欢迎任何提示,无论如何感谢您阅读我。

标签: javascriptreact-nativereduxreact-redux

解决方案


尝试console.log(this.props.todos) 由于您将整个 redux 存储状态映射到todos您应该在以下位置找到它的对象this.props.todos


推荐阅读