I have a class used to render a list of users from a database
export default class Users extends React.Component {
constructor() {
super()
this.state = {
data : [] //define a state
}
}
renderUsers = () => {
useEffect(() => {
fetch('exemple')
.then((response) => response.json())
.then((json) => this.setState({data: json.result})) // set returned values into the data state
.catch((error) => console.error(error))
}, []);
return this.state.data.map((value,key)=>{ // map state and return some views
......
})
}
render() {
return (
<View style={{ flex: 1 }}>
{this.renderUsers()} //render results
</View>
);
}
}
The problem is this code will throw the following error :
Invalid Hook call, Hooks can be called only inside of the body ponent
I think is not possible to use hooks inside class ponent.. If it's not possible what is the best approach to fetch data from server inside this class ?
I have a class used to render a list of users from a database
export default class Users extends React.Component {
constructor() {
super()
this.state = {
data : [] //define a state
}
}
renderUsers = () => {
useEffect(() => {
fetch('exemple.')
.then((response) => response.json())
.then((json) => this.setState({data: json.result})) // set returned values into the data state
.catch((error) => console.error(error))
}, []);
return this.state.data.map((value,key)=>{ // map state and return some views
......
})
}
render() {
return (
<View style={{ flex: 1 }}>
{this.renderUsers()} //render results
</View>
);
}
}
The problem is this code will throw the following error :
Invalid Hook call, Hooks can be called only inside of the body ponent
I think is not possible to use hooks inside class ponent.. If it's not possible what is the best approach to fetch data from server inside this class ?
Share Improve this question asked Jul 24, 2020 at 21:15 anehmeanehme 5661 gold badge7 silver badges19 bronze badges 1-
1
ponentDidMount
. – Jared Smith Commented Jul 24, 2020 at 21:16
2 Answers
Reset to default 6You cannot use hooks in a class ponent. Use ponentDidMount
instead.
Hooks can be used only in functional ponents.
You could rewrite your ponent to be a functional one like so:
export default Users = () => {
const [data, setData] = useState([]);
useEffect(() => {
fetch('exemple.')
.then((response) => response.json())
.then((json) => setData(json.result)) // set returned values into the data state
.catch((error) => console.error(error))
}, []);
const renderUsers = () => {
return data.map((value, key) => {
// DO STUFF HERE
})
}
return (
<View style={{ flex: 1 }}>
{renderUsers()} //render results
</View>
)
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744873126a4598382.html
评论列表(0条)