reactjs - 从道具中的函数反应返回字符串
问题描述
在反应中,我需要根据函数的返回值设置一个道具。我想尽量避免为此使用状态,并且我从 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();
};
解决方案
//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()}}
/>
推荐阅读
- python - Numpy:计算数组中索引出现的最佳方法
- java - 如何使用 Dto 类中的实体类进行映射并使用存储库来执行此操作,但我没有得到它
- docker - 适用于 Windows 容器的 Amazon Corretto 11 docker 映像
- reactjs - SVG在页面更改时变黑
- javascript - Dropzonejs度假村附加图像
- javascript - 验证验证码的自动化脚本
- mysql - Wordpress 在安装过程中显示空白页
- robotframework - 机器人框架如何处理没有资源的元素或如何自定义插入唯一文本
- python - 试图在一天中的某些时间触发 if 语句
- typescript - 将 markdown 值传递到 Vue.js 中的另一个页面