如何拼接字符串获取正确变量与函数名以复用React状态更新函数
React 动态访问对应useState状态及调用相关函数(不重构为对象状态)
问题场景
现有如下React代码,包含两组useState状态及对应的setter函数,希望通过同一个handleAddAdditionalProperty函数,根据传入的type参数匹配对应的状态变量、setter函数及getXXXRow函数,避免代码重复,且不想大量重构现有代码、不使用对象存储状态。
原代码
import { useState } from 'react'; import Button from '你的Button组件路径'; const [questionsAdditionalProperties, setQuestionsAdditionalProperties] = useState([]); const [usersAdditionalProperties, setUsersAdditionalProperties] = useState([]); // 假设存在对应的生成行函数 const getQuestionsAdditionalPropertiesRow = (type, key) => { // 生成questions对应的行逻辑 }; const getUsersAdditionalPropertiesRow = (type, key) => { // 生成users对应的行逻辑 }; const handleAddAdditionalProperty = (type) => { //how to concatenate this valiable name to access the value in state? const key = `${type}AdditionalProperties.length`; let newAdditionalProperty = []; newAdditionalProperty.push( // how to concatenate the function name to call the correct hook? getQuestionsAdditionalPropertiesRow(type, key) ); // how to concatenate the function name to call the correct hook and the variable name to use spread? setQuestionsAdditionalProperties([...questionsAdditionalProperties, ...newAdditionalProperty]); }; <p className="right" onClick={e => handleAddAdditionalProperty("questions")}> <Button variant="primary">Add Question Additional Property</Button> </p> <p className="right" onClick={e => handleAddAdditionalProperty("users")}> <Button variant="primary">Add Users Additional Property</Button> </p>
解决方案
不用字符串拼接访问变量(组件内变量属于函数作用域,无法通过全局对象访问),而是通过映射对象关联type与对应的状态、setter、生成函数,无需修改原有状态定义,仅新增映射层即可实现需求:
修改后的核心代码
// 新增映射对象,关联type和对应的状态、setter、生成函数 const stateMap = { questions: { state: questionsAdditionalProperties, setter: setQuestionsAdditionalProperties, getRow: getQuestionsAdditionalPropertiesRow }, users: { state: usersAdditionalProperties, setter: setUsersAdditionalProperties, getRow: getUsersAdditionalPropertiesRow } }; const handleAddAdditionalProperty = (type) => { // 从映射中取出对应的数据,容错处理避免传错type const target = stateMap[type]; if (!target) return; const { state, setter, getRow } = target; const key = state.length; const newAdditionalProperty = [getRow(type, key)]; // 调用对应的setter更新状态 setter([...state, ...newAdditionalProperty]); };
说明
- 映射对象
stateMap仅做关联作用,完全保留原有状态的定义方式,无需大量重构代码 - 相比字符串拼接访问变量,映射方式更安全、可读性更强,也避免了作用域相关的问题
- 新增了容错逻辑,防止传入不存在的
type导致报错
内容的提问来源于stack exchange,提问作者user3174311
相关产品推荐
相关产品推荐

