簡體   English   中英

我可以將 class 組件更改為功能組件嗎? - Reactjs

[英]Can I change class component into functional component? - Reactjs

我使用 class 組件。 只是測試它。 現在我不知道如何將其轉換為功能。 這是我的代碼:

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;

我應該在我的 redux 中使用此代碼,我需要將其轉換為功能組件

我想要這樣的東西:

export const PostList = () =>{
   return (
    //my code using axios,       
   )
}```



 

對於功能組件,您應該使用hooks而不是分類組件默認statecomponentDidMount 所以要定義一個新的 state 你需要使用useStatecomponentDidMount你需要使用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;

既然你想使用函數式組件,你就必須使用React Hooks

在您的情況下,使用useStateuseEffect掛鈎可以幫助分別獲得與this.statecomponentDidMount()相同的結果。

 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM