首页 > 解决方案 > 从道具中的函数反应返回字符串

问题描述

在反应中,我需要根据函数的返回值设置一个道具。我想尽量避免为此使用状态,并且我从 localstorage 中获取一个变量,以便用户可以从他们离开的地方继续。这是从本地存储返回值的函数:

const getCustomerId = () => {
    return getItem('customerId').toString();
};

然后我有一个需要从本地存储访问 customerId 的提供程序。我尝试将函数返回值作为道具传递,但道具应该是一个字符串,并且它仍然给它一个函数:

<ProfileProvider
      id="1"
      email={user?.email}
      setSelectedCustomer={handleChangeCustomer}
      customerId={getCustomerId}
    >

同样,当handleChangeCustomer调用 时,getCustomerId应该从其中调用 以进行更改。customerId 的 prop 也应该使用来自 localStorage 的更新值。

我不确定在不使用状态的情况下如何做到这一点。

处理客户功能:

const handleChangeCustomer = id => {
    
    setLocalCustomer(id);
    getCustomerId();
  };

标签: reactjs

解决方案


//Have you tried adding the parentheses at the end?

<ProfileProvider
      id="1"
      email={user?.email}
      setSelectedCustomer={handleChangeCustomer}
      customerId={getCustomerId()}
    />


//Or adding it to a arrow function:

    <ProfileProvider
          id="1"
          email={user?.email}
          setSelectedCustomer={handleChangeCustomer}
          customerId={()=>{getCustomerId()}}
        />


推荐阅读