【问题标题】:Issue trying to re-render react parent component from child尝试从子组件重新渲染反应父组件的问题
【发布时间】:2020-05-17 17:21:33
【问题描述】:

试图从子组件回调中重新渲染父组件。在支付按钮中,我调用 axios 来更新状态,然后我需要父级显示这个新的更新状态,所以我尝试将“false”状态设置为 true,我希望这会触发重新渲染。

错误:

Line 28:4:  Expected an assignment or function call and instead saw an expression

来自父母


    const [success, setSuccess] = useState(false);

<h4>
                    Purchase 5 more post's : <PaymentButton name="more post" price={5} description="create more post"
                        object={
                { email: user.email, max_posts: user.max_posts + 5 }
                        }
                        success ={()=>setSuccess(true)}

                    />

                </h4>

来自孩子

const PaymentButton = ({ name, price, description,object }) => {

    const handleToken = async (token, addresses) => {
        const response = await axios.post('http://localhost:3000/api/payment/checkout', {
            token,
            product: { name, price, description }
        });

        const { status , resolved} = response.data;

        console.log('Response:', response);
        console.log('network_status :', resolved);
        console.log(JSON.stringify(object))


        if (status === 'succeeded' && resolved ==='approved_by_network') {
            toast('Success! Purchase Approved. ', { type: 'success' });
            return axios.put('http://localhost:3000/api/users/getuser', { ...object });
            object.success


        } else {
            toast('Something went wrong, contact site admin about this', { type: 'error' });
        }
    };


【问题讨论】:

  • 您能否准确说明您要做什么,并发布您遇到的错误?
  • 我试图澄清一点,对此感到抱歉!
  • 好的,我想我知道发生了什么。如果请求成功,你想调用一个从父组件传下来的success函数,它会更新父组件的状态并触发父组件的重新渲染。
  • 我认为问题 #1 是 success 函数现在不在 object 中。看起来您将 success 作为单独的道具传递给孩子,因此您需要将其添加到列表 const PaymentButton = ({ name, price, description, object, success }),然后调用 success() 代替您的 object.success 行。
  • {() =&gt; setSuccess(true)} 传递给子组件的那一行,实际上是在给子组件一个要调用的函数。所以你需要确保你实际上调用了父函数给你的函数,就像你调用任何其他函数一样。

标签: javascript node.js reactjs express stripe-payments


【解决方案1】:

您可能需要通过以下方式反转 true 状态:

!success

【讨论】:

    猜你喜欢
    • 2018-09-19
    • 2018-08-12
    • 2019-06-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2021-12-01
    相关资源
    最近更新 更多