I use class component. Just testing it. Now I don't know how to convert it into functional. This is my code:
class PostList extends Component {
constructor(props) {
super(props);
this.state = {
info: []
};
}
componentDidMount() {
axios
.get("https://api2.binance.com/api/v3/ticker/24hr")
.then((response) => {
this.setState({
info: response.data
});
console.log(response.data);
});
}
render() {
const { info } = this.state;
return (
<div>
<h2>post!</h2>
{info.map((user) => (
<div key={user.symbol}>
<h6>{user.priceChange}</h6>
</div>
))}
</div>
);
}
}
export default PostList;
I should use this code in my redux and I need to convert it into functional component
I want something like this:
export const PostList = () =>{
return (
//my code using axios,
)
}```
CodePudding user response:
For functional component, you should use hooks
instead of classify components default state
and componentDidMount
. So for define a new state you need to use useState
and for componentDidMount
you need to use useEffect
:
const PostList = (props) => {
const [state,setState] = useState({info:[]});
useEffect(()=>{
axios
.get("https://api2.binance.com/api/v3/ticker/24hr")
.then((response) => {
setState({
info: response.data
});
console.log(response.data);
});
},[])
const { info } = state;
return (
<div>
<h2>post!</h2>
{info.map((user) => (
<div key={user.symbol}>
<h6>{user.priceChange}</h6>
</div>
))}
</div>
);
}
export default PostList;
CodePudding user response:
Since you want to use functional components, you will have to use React Hooks!
In your case, using the useState
and useEffect
hooks can help to achieve the same result as this.state
and componentDidMount()
respectively.
const PostList = (props) => {
const [state,setState] = useState({info:[]});
useEffect(()=>{
axios
.get("https://api2.binance.com/api/v3/ticker/24hr")
.then((response) => {
setState({
info: response.data
});
console.log(response.data);
});
},[])
return (
<div>
<h2>post!</h2>
{state.info.map((user) => (
<div key={user.symbol}>
<h6>{user.priceChange}</h6>
</div>
))}
</div>
);
}
export default PostList;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>