import React from 'react'
import './App.css'
import { Description } from './Description'
/**
*
* @type {React.FC}
*/
export const App = () => {
return (
<div>
<div className="dogdisplay">
<Description />
</div>
</div>
)
}
import React, { useState } from 'react'
import { DogImage } from './DogImage'
const [dogUrl, setDogUrl] = useState(
'https://images.dog.ceo/breeds/spaniel-brittany/n02101388_6057.jpg',
)
const API_URL = 'https://dog.ceo/api/breeds/image/random'
export const Description = () => {
return (
<div>
<title>React.com</title>
<p>これは犬のサイトです。</p>
<img src={dogUrl} />
<button onClick={() => setDogUrl(<DogImage url={API_URL} />)}>
update
</button>
</div>
)
}
export const DogImage = props => {
fetch(this.props.url)
.then(res => {
res.json()
})
.then(data => {
return data.message
})
}
What is this Cannot read properties of null (reading ‘useState’)?
Cannot read properties of null (reading ‘useState’)?
error.
I want the dog image to change when I press the refresh button and then the refresh button.
>Solution :
Hooks can only be called inside of the body of a function component.
import React, {useState} from 'react'
import { DogImage } from './DogImage'
const API_URL = 'https://dog.ceo/api/breeds/image/random'
export const Description = () => {
const [dogUrl, setDogUrl] = useState(
'https://images.dog.ceo/breeds/spaniel-brittany/n02101388_6057.jpg',
)
return (
<div>
<title>React.com</title>
<p>これは犬のサイトです。</p>
<img src={dogUrl} />
<button onClick={() => setDogUrl(<DogImage url={API_URL} />)}>
update
</button>
</div>
)
}