簡體   English   中英

我怎樣才能把這個 React class 組件變成一個功能組件?

[英]How can i turn this React class component into a functional component?

我正在我的 react/mui 應用程序中實施一種 Braintree 支付方式。 我找到了一種可行的方法,但它位於 class 組件中。 如何將此信息轉換為適當的功能組件?

    const BraintreeDropInPaymentMethod = () => {
    class Store extends React.Component {
        instance;

        state = {
            clientToken: '<BRAIN TREE KEY>'
        };

        async componentDidMount() {
            const response = await fetch("server.test/client_token");
            const clientToken = await response.json();

            this.setState({
                clientToken,
            });
        }

        async buy() {
            const { nonce } = await this.instance.requestPaymentMethod();
            await fetch(`server.test/purchase/${nonce}`);
        }

        render() {
            if (!this.state.clientToken) {
                return (
                    <div>
                        <h1>Loading...</h1>
                    </div>
                );
            } else {
                return (
                    <div>
                        <DropIn
                            options={{ authorization: this.state.clientToken }}
                            onInstance={(instance) => (this.instance = instance)}
                        />
                        <Button
                            variant='contained'
                            onClick={this.buy.bind(this)}
                        >
                            Create Account
                        </Button>
                        <Button
                            variant='outlined'
                            sx={{ marginLeft: 3 }}
                            color='warning'
                            onClick={(e) => handleCancelAccountCreation(e)}
                            href='/store-front'
                        >
                            Cancel
                        </Button>
                    </div>
                );
            }
        }
    }

    const [user, setUser] = useState({})
    const handleCancelAccountCreation = (event) => {
        setUser({})
        document.getElementById('signInBtn').hidden = false
    }

    return (
        <Store/>
    )
}

這是我的嘗試,但我不知道應該如何處理componentDidMount() 我知道在某些情況下如何處理useState ,除了這個。 另外,如何以功能格式處理“實例”部分? 謝謝。

    const BraintreeDropInPaymentMethod = () => {

    const [token, setToken] = useState('<BRAIN TREE KEY>')
    const [user, setUser] = useState({})

    const contactServer = async () => {
        const res = await fetch('server.test/client_token')
        const clientToken = await res.json()
        console.log(clientToken)
        setToken(token)
    }

    const buy = async () => {
        const { nonce } = await this.instance.requestPaymentMethod()
        await fetch(`server.test/purchase/${nonce}`)
    }

    const handleCancelAccountCreation = (event) => {
        setUser({})
        document.getElementById('signInBtn').hidden = false
    }

    const createAccountOptions = () => {
        if (!token) {
            return (
                <div>
                    <h1>Loading...</h1>
                </div>
            ) else {
                return (
                    <div>
                        <DropIn
                            options={ authorization: {setToken})
                            onInstance={(instance) => (this.instance = instance)}
                        />
                        <Button
                            variant="contained'
                            onClick={buy}
                        >
                         Create Account
                        </Button
                            variant='outlined'
                            sx={{ marginLeft: 3 }}
                            color='warning'
                            onClick={(e) => handleCancelAccountCreation(e)}
                            href='/store-front'
                        >
                        <Button>
                            Cancel
                        </Button>
                    </div>
                )
            }
        }
    }

    return(
        <>
            <createAccountOptions/>
        </>
    )   
}

componentDidMount()的功能等價物是useEffect掛鈎

在這種情況下,您將更改此:

    async componentDidMount() {
        const response = await fetch("server.test/client_token");
        const clientToken = await response.json();

        this.setState({
            clientToken,
        });
    }

變成這樣:

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const response = await fetch("server.test/client_token");
    const clientToken = await response.json();
    setState((old) => clientToken);
  };

使用帶有空數組的useEffect掛鈎作為依賴項,使得其中的 function 僅在組件安裝時運行一次。

暫無
暫無

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

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