【发布时间】: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 中使用 <Provider></Provider> 来捕捉每一个变化,但首先,我需要了解我错了什么?
它是否完全连接?在我遵循的示例中,我没有看到connect()。另外,我不确定我是否正确使用了type。
提前谢谢你。
【问题讨论】:
标签: react-native redux react-redux