【发布时间】:2018-08-11 01:23:56
【问题描述】:
这是我在 React Native 中使用 Redux 的第一个项目,我有一个组件(MyApp),我要在 index.js 中导入它。但它给出了上述错误。
index.js -
import React from 'react';
import { AppRegistry } from 'react-native';
import MyApp from './component/MyApp';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from './reducers';
import thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(thunk));
const App = () => {
<Provider store={store}>
<MyApp/>
</Provider>
}
AppRegistry.registerComponent('learningRedux', () => App);
MyApp.js
import React, { Component } from 'react';
import {
Text, View, TouchableHighlight
} from 'react-native';
import { connect } from 'react-redux';
import { fetchPeopleFromAPI } from '../actions/index';
export class MyApp extends Component {
render() {
const { people, isFetching } = props.people
return (
<View style={{
margin: 100,
paddingLeft: 20,
paddingRight: 20
}}
>
<Text style={{
fontSize: 30,
textAlign: 'center'
}}> Redux App </Text>
<TouchableHighlight style={{
backgroundColor: 'blue',
height: 60,
justifyContent: 'center',
alignItems: 'center'
}}
onPress={() => {
props.getPeople
}}>
<Text style={{
color: 'white'
}}> Fetch Data </Text>
</TouchableHighlight>
{
isFetching && <Text> Loading... </Text>
}
{
people.length ? (
people.map((person, index) => {
return (
<View key={index}>
<Text> Name : {person.name} </Text>
<Text> Birth Year : {person.birth_year} </Text>
</View>
)
}
)
) : null
}
</View>
);
}
}
mapStateToProps = (state) => {
return {
people: state.peopleReducer
}
}
mapDispatchToProps = (dispatch) => {
return {
getPeople: () => dispatch(fetchPeopleFromAPI())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(MyApp)
我尝试了另一种方法,通过创建一个 const MyApp 而不是类,并通过将 props 作为参数传递来使用箭头函数,然后只使用 return(而不是渲染),但它仍然无法正常工作。 谢谢。
【问题讨论】:
标签: react-native redux react-redux