私は経験している問題に関するサイトで多くの質問と回答を見てきました。リアクタとRedux - 初期ロード時のデータ
私はReact、React Router、Reduxで通常の設定をしています。私のトップレベルのコンポーネントは次のとおりです。
import React from 'react';
import Main from './Main';
const App =() => (
<div>
<Main />
</div>
);
export default App;
マイMain.jsx
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import GroupingContainer from '../containers/Grouping';
import HomeContainer from '../containers/Home';
const Main =() => (
<main>
<Switch>
<Route exact path='/' component={HomeContainer} />
<Route path='/groupings/:id' component={GroupingContainer} />
</Switch>
</main>
);
export default Main;
そして最後に、私は私のGrouping.jsxとGroupingContainer.jsx
を持っている:私は、次のコードを持っている私のApp.jsxインサイド// Imports
const reducers = {
main: baseReducer,
form: formReducer,
};
const reducer = combineReducers(reducers);
const store = createStore(
reducer,
applyMiddleware(thunk),
);
store.dispatch(actions.auth.setCurrentUser());
// store.dispatch(actions.api.fetchLineup());
ReactDOM.render(
<Provider store={store}>
<HashRouter>
<App />
</HashRouter>
</Provider>
,
document.getElementById('root')
);
import React, { Component } from 'react';
function loadGrouping(props, groupingId) {
const grouping = props.main.groupings.find(
(g) => g.id === groupingId
);
if (!grouping) {
props.dispatch(api.fetchGrouping(groupingId));
}
}
class Grouping extends Component {
constructor(props) {
super(props);
loadGrouping(props, props.groupingId);
}
componentWillReceiveProps(nextProps) {
console.log('Next: ', nextProps);
if (nextProps.match && nextProps.match.params.id !== this.props.match.params.id) {
loadGrouping(this.props, nextProps.groupingId);
}
}
render() {
const grouping = this.props.main.groupings.find(
(lg) => lg.id === this.props.groupingId
);
return (
<div>
<h1>{grouping.name}</h1>
</div>
);
}
}
export default Grouping;
GroupingCon tainer.jsx
import { connect } from 'react-redux';
import Grouping from '../components/Grouping';
const mapStateToProps = (state, ownProps) => {
return {
groupingId: parseInt(ownProps.match.params.id, 10),
...state,
};
};
const mapDispatchToProps = (dispatch) => ({
dispatch,
});
const GroupingContainer = connect(
mapStateToProps,
mapDispatchToProps,
)(Grouping);
export default GroupingContainer;
それが返さストアにグループ化し、グループstate.main.groups
の配列に、私は2つの問題があります追加し、別のアクションを起動要求した後。私はグループの一つにルートパスから、次のフローを参照する場合:
http://localhost:3000 -> http://localhost:3000/#/groupings/19
私はメッセージが表示されます。APIリクエストが終了するまでの短い秒Uncaught TypeError: Cannot read property 'name' of undefined
と{grouping.name}
を移入し、私は完全リフレッシュを行うときグループURLのページのhttp://localhost:3000/#/groupings/19
アプリケーションがまったく読み込まれず、同じものが返されるUncaught TypeError: Cannot read property 'name' of undefined
Reactを約2か月間使用していて、実際にコンポーネントロード時にAPIリクエストを使用し始めました。私は実際にAPI要求をどこに配置して、ビューのレンダリングが終了してエラーになるのを防ぐことができないのか分かりません。
助けていただけたら幸いです!
ありがとうございます!
それは私が尋ねたhttps://stackoverflow.com/questions/39381378/whats-the-best-way-to-deal-with-undefined-props-in-react-jsを助けるかもしれない、この記事を参照してください質問は似ており、非常にクールな応答を得た –