[TIL]21.05.12
1.API情報を受信し、ステータスに値を割り当てる
userEffect()を使用してAPIの情報を文字列としてendpointに受信し、fectchMoviesという関数を使用してstateに値を割り当てます.
const [Movies, setMovies] = useState([]);
const [MainMovieImage, setMainMovieImage] = useState(null);
const [CurrentPage, setCurrentPage] = useState(0);
useEffect(() => {
const endpoint = `${API_URL}movie/popular?api_key=${API_KEY}&language=en-US&page=1`;
fetchMovies(endpoint);
// Axios.get(endpoint)
// .then(response => {
// setMovies([...response.results])
// setMainMovieImage(response.results[0])
// })
// endpoint에 받은 값(API)을 fetch가 가져온다? 그렇게보면 될듯
// 그 값이 response에 담긴다. 하지만 response만으로 response을 읽을 수 없기에
// json()을 사용해줌.
}, [])
const fetchMovies = (endpoint) => {
fetch(endpoint)
.then(response => response.json())
.then(response => {
console.log(response.results[0])
setMovies([...response.results]); // response를 콘솔로 찍어보면 객체임 results는 사진담겨있는 키, property인 듯..
setMainMovieImage(response.results[0]);
setCurrentPage(response.page);
});
}
2.MainImageコンポーネントの作成
低Movie APIに含まれる情報は、以下のようにオブジェクトです.
MainImage Componentを作成する場合、propsを使用してオブジェクトの値を使用できます.
import React from 'react';
function MainImage(props) {
return (
<div style={{
backgorund: `linear-gradient(to bottom, rgba(0,0,0,0)
39%, rgba(0, 0, 0, 0)
41%, rgba(0, 0, 0, 0.65)
100%),
url('${props.image}'), #1c1c1c`,
height: '500px',
backgroundSize: '100%, cover',
backgroundPosition: 'center, center',
width: '100%',
position: 'relative'
}}>
<div>
<div style={{ position: 'absolute', maxWidth: '500px', bottom: '2rem', marginLeft: '2rem' }}>
<h2 style={{ color: 'white' }}>{props.title}</h2>
<p style={{ color: 'white', fontSize: '1rem' }}>{props.text}</p>
</div>
</div>
</div>
);
}
export default MainImage;
しかし,我々がコードを記述する目的は,APIに入力された情報,オブジェクトのキー値を画像に出力することであるが,CSSレイアウトの情報のみを出力し,本当に重要な画像は出力しない.
const test1 = document.querySelector('.test');
let makeImg = document.createElement('img');
makeImg.setAttribute('src', 'http://image.tmdb.org/t/p/w1280/fPGeS6jgdLovQAKunNHX8l0avCy.jpg');
test1.append(makeImg);
正常な出力が見えます
勝手にDOMに入れず、リアクターでUSEffectを使い、stateに正確に値を割り当てることで、明日も画像の出力に努めます.やってみよう...
明日やること
DomではなくuseEffectを使用して画像をランダムに出力し、stateに値を正しく割り当てると、コードが実装され、コード内で正常に出力されます.授業と同じように、どこが間違っているのかよく確認します.
鼻翼を広げて
Reference
この問題について([TIL]21.05.12), 我々は、より多くの情報をここで見つけました https://velog.io/@juho00ng/TIL21.05.12テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol