です。反応コンポーネントのjsonから変数にアクセスしようとしています。jsonからのアクセスの値は
これは私が取得していますJSONです:
{
"id": 5,
"title": "Hello",
"text": "Hello, this is my first article...",
"picture": "pic",
"comments": [],
"user": {
"id": 3,
"name": "Anonim",
"password": "123456"
}
}
添付のユーザーがポストを作成した人です。 添付のコメントは、この投稿に関連するコメントのリストです。私は次のことをやっているルーティングで :私は、ユーザーとコメントをアクセスすることはできませんなぜ
<Switch>
<Route path='/' exact component={PostsPage} />
<Route path='/:id' exact component={PostProfilePage} />
</Switch>
では
class PostProfile extends Component {
constructor(props){
// Pass props to the parent component
super(props);
// Set initial state
this.state = {
// State needed
post: []
};
}
componentDidMount() {
this.fetchPost();
}
fetchPost() {
const {match} = this.props
const id = match.params.id
console.log(id)
fetch('/'+id)
.then(res => {
return res.json();
})
.then(data => {
this.setState({
post: data
});
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<div>
<li> {this.state.post.title} </li>
<li> {this.state.post.text} </li>
</div>
)
}
}
export default withRouter(PostProfile)
クラスコンポーネントを反応
<li> {this.state.post.user.name} </li>
<li> {this.state.post.comments...} </li>
動作しませんか? さまざまなコンポーネントでユーザーとコメントを取得できますか? (fetchメソッドを何度も呼び出さない)
ありがとうございます!
を 'this.state.post'何かを得ていますか? – jmargolisvt
はい、JSON – Alex
と同じですが、コンソールにエラーが表示されませんか?最初のレンダリングで? – joelbarbosa