Reactjs mapStateToProps不返回数据,数据未定义
我的问题是MapStateTops返回未定义的。可能我在状态下调度时遇到了一些问题,或者可能在数据来自服务器之前进行应用程序渲染?我不明白。所以应用程序在没有redux的情况下可以正常工作,只需使用componentDidMount,但我在redux方面有一些问题 因此,我有一个顶级组件应用程序:Reactjs mapStateToProps不返回数据,数据未定义,reactjs,react-native,react-redux,Reactjs,React Native,React Redux,我的问题是MapStateTops返回未定义的。可能我在状态下调度时遇到了一些问题,或者可能在数据来自服务器之前进行应用程序渲染?我不明白。所以应用程序在没有redux的情况下可以正常工作,只需使用componentDidMount,但我在redux方面有一些问题 因此,我有一个顶级组件应用程序: const App = () => { return ( <Provider store={store}> <Screen /> <
const App = () => {
return (
<Provider store={store}>
<Screen />
</Provider>
)
}
两种类型的行动:
export const fetchData = (newPhotos) => async (dispatch) => {
function onSuccess(success) {
dispatch({
type: FETCH_DATA,
payload: success})
return success
}
function onError(error) {
dispatch({type: FETCH_FAILED, error})
}
try {
const URL = 'https://api.unsplash.com/photos/?client_id=cf49c08b444ff4cb9e4d126b7e9f7513ba1ee58de7906e4360afc1a33d1bf4c0';
const res = await fetch(URL);
const success = await res.json();
console.log(success);
return onSuccess(success);
} catch (error) {
return onError(error)
}
};
减速器:
const initialState = {
data: []
}
export default dataReducer = (state = initialState, action) => {
console.log(action);
switch (action.type) {
case FETCH_DATA:
return {
data: action.payload
}
case FETCH_FAILED:
return {
state
}
default: return state;
}
}
联合收割机减速器:
export default combineReducers({
fetchedData: dataReducer
});
和我的渲染组件:
class HomeScreen extends Component {
render() {
console.log(this.props)
const {navigation, data} = this.props;
return (
<ScrollView>
<Header />
<ImageList navigation={navigation} data={data}/>
</ScrollView>
)
}
}
const mapStateToProps = state => {
return {
data: state.fetchedData.data
}
}
export default connect(mapStateToProps, {fetchData})(HomeScreen);
类主屏幕扩展组件{
render(){
console.log(this.props)
const{navigation,data}=this.props;
返回(
)
}
}
常量mapStateToProps=状态=>{
返回{
数据:state.fetchedData.data
}
}
导出默认连接(MapStateTops,{fetchData})(主屏幕);
fetchData
操作本身不会被调用。您需要显式地调用它(在componentDidMount
中,可能还有componentdiddupdate
)如下
state.fetchedData是否也未定义?
class HomeScreen extends Component {
render() {
console.log(this.props)
const {navigation, data} = this.props;
return (
<ScrollView>
<Header />
<ImageList navigation={navigation} data={data}/>
</ScrollView>
)
}
}
const mapStateToProps = state => {
return {
data: state.fetchedData.data
}
}
export default connect(mapStateToProps, {fetchData})(HomeScreen);
class HomeScreen extends Component {
componentDidMount() {
this.props.fetchData(/* I don't know where you are going to take newPhotos argument */);
}
render() {
//...
}
}