【发布时间】:2018-05-13 10:09:49
【问题描述】:
我正在向 reactjs 迈出第一步。我使用 fetch 创建了the movie db API 的服务。我已经完成了列出电影的名称。
我想要做的是拥有一个完全独立的组件。一个连接到 API 的组件和其他组件负责呈现该信息。
现在我在同一个组件中拥有这两种行为:(
谁能帮帮我?
这是我的代码
import React, { Component } from 'react';
const listUrl = 'https://api.themoviedb.org/4/list/5?api_key=a6ebd775daadc2ec23c371e873e20a02&page=1';
class ListingService extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
fetch(listUrl)
.then((response) => {
if (!response.ok) {
throw Error('Network request failed');
}
return response;
})
.then((response) => {
return response.json();
})
.then((response) => {
this.setState({
movieName: response.results.map((movie) => {
return (
<li key={movie.id}>{movie.title}</li>
);
}),
});
}, () => {
this.setState({
requestFailed: true,
});
});
}
render() {
if (this.state.requestFailed) return <p>Failed!</p>;
if (!this.state.movieName) return <p>Loading...</p>;
return (
<div>
<h2><ol>{this.state.movieName}</ol></h2>
</div>
);
}
}
我有一个带有此代码的父组件:
import React from 'react';
import ListingService from '../../services/listing/index';
const List = () => {
return (
<div>
<b>List of movies</b>
<ListingService />
</div>
);
};
export default List;
我应该为此使用 redux 吗?
【问题讨论】:
-
你不需要 redux。您可以做的最基本的事情就是从
ListingService渲染的内容中创建另一个组件,然后将其状态作为道具传递给新组件。这不是你要问的吗?
标签: javascript reactjs design-patterns service components