【问题标题】:Dispatching Redux Data and Get the State调度 Redux 数据并获取状态
【发布时间】:2019-10-27 16:12:24
【问题描述】:

在使用 React Native 和 Redux 开发应用程序时,我坚持使用 Redux 实现。我第一次这样做并关注this example

我已经安装了 Redux 和 React Native Navigation。我想保存包含国家数据的状态(用户选择了一个国家,并希望在浏览所有屏幕时保留选择)。

很好。我创建了一个可以在所有屏幕上看到的组件,如下所示:

        LinksScreen.navigationOptions = {
         headerTitle: 'Links',
         headerRight: <CountriesPickButton/>,
       };

接下来,我将按钮可视化并等待组件发生变化。默认情况下,它应该显示主要国家。接下来,用户单击该按钮,它会打开一个模式,其中有一个下拉菜单。例如,我向您展示了获取国家/地区的默认设置:

import { connect } from 'react-redux'
import store from '../../redux/countries'

export default class CountriesPick extends Component {

render() {....  // here is the button and modal, etc. It's work. 
}

 constructor(props, context) {

    super(props, context);

    this.state = store.getState();

    store.subscribe(() => {

      this.setState(store.getState());

    });

    this.defaultCountry(251);
}


async defaultCountry(countryId) {

    return fetch(URL)
      .then((response) => response.json())
      .then((responseJson) => {
        for (const key of Object.keys(responseJson.result)) {
          // this works for current screen: this.setState({ defaultCountry: responseJson.result[key], selectedCountry: responseJson.result[key].country_id });
          store.dispatch({ defaultCountry: responseJson.result[key], selectedCountry: responseJson.result[key].country_id ,  type: 'countries' });

        }

        return responseJson.result;
      })
      .catch((error) => {
        console.error(error);
      });

state = {
  showModal: false,
  countries: [],
  selectedCountry: 0,
  defaultCountry: [], 
  type: 'countries'
  };
  }

没有store.dispatch({})我可以用国家改变状态,但它不能在屏幕之间共享。那是因为我是从 Redux 开始的。

这里是 Redux 代码():

import { createStore } from 'redux'

const defaultState = {
  showModal: false,
  countries: [],
  selectedCountry: 0,
  defaultCountry: [], 
  type: 'countries'
};

function store(state = defaultState) {

  return state;
}

export default createStore(store);

有些事情不应该是这样。当我调用store.dispatch({...}) 时,它没有改变状态,它返回默认数组。我想我应该在 App.js 中使用 &lt;Provider&gt;&lt;/Provider&gt; 来捕捉每一个变化,但首先,我需要了解我错了什么?

它是否完全连接?在我遵循的示例中,我没有看到connect()。另外,我不确定我是否正确使用了type

提前谢谢你。

【问题讨论】:

    标签: react-native redux react-redux


    【解决方案1】:

    这里的问题如下:

    1. 您提供的链接示例至少可以说是不好的。不要跟随它
    2. 您说要使用react-native-navigation,但您提供的代码来自react-navigation。我建议使用后者,尤其是对于初学者
    3. 您的 createStore 代码不起作用,因为 store 的 reducer 应该是 stateaction 的函数

    话虽如此,您绝对应该看到 Basic Tutorial 的 redux 示例。在使用 redux 反应时,您几乎不必执行 store.getState()store.dispatch(),因为 react-reduxpackage(包含在我链接的教程中)将为您执行此操作。相反,您将声明您的商店状态和组件接收的道具之间的依赖关系

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2019-02-20
      • 2017-06-08
      • 1970-01-01
      • 2021-03-13
      相关资源
      最近更新 更多