【问题标题】:mapStateToProps returns no data, data is undefinedmapStateToProps 不返回数据,数据未定义
【发布时间】:2019-10-09 23:19:02
【问题描述】:

我的问题是 mapStateToProps 返回未定义。也许我在状态中调度或在数据来自服务器之前呈现应用程序时遇到了一些问题?我无法理解。所以应用程序在没有 redux 的情况下只需要 componentDidMount 就可以正常工作,但是我对 redux 有一些问题 所以我有一个顶级组件App:

const App = () => {
  return (
    <Provider store={store}>
      <Screen />
    </Provider>
  )
}

我有 thunk meddleware 的商店:

const store = createStore(reducer, applyMiddleware(ReduxThunk));

两种类型的动作:

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);

【问题讨论】:

  • state.fetchedData 是否也未定义?

标签: reactjs react-native react-redux


【解决方案1】:

fetchData 操作不会自行调用。你需要明确地调用它(在componentDidMount,可能还有componentDidUpdate),比如

class HomeScreen extends Component {
  componentDidMount() {
    this.props.fetchData(/* I don't know where you are going to take newPhotos argument */);
  }

  render() {
     //...
  }
}

【讨论】:

    猜你喜欢
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2021-11-22
    • 2014-10-13
    • 1970-01-01
    • 2021-08-01
    • 2017-05-31
    相关资源
    最近更新 更多