Javascript 如何映射从数据库中获取的元素?

Javascript 如何映射从数据库中获取的元素?,javascript,reactjs,mongodb,Javascript,Reactjs,Mongodb,我想问您如何从数据库映射元素。我基本上想制作这样的东西:name={name},isOn={isOn} 以及应获得指定数据的组件的代码: const Islbutton=props=>{ const[name,setName]=useState; const[isOn,setIsOn]=useStatetrue; //一些功能 回来 切换图像}/> ; } 您需要使用useEffect来处理函数组件中的外部属性更改。参见下面的示例 const{Component,useState,useffe

我想问您如何从数据库映射元素。我基本上想制作这样的东西:name={name},isOn={isOn}

以及应获得指定数据的组件的代码:

const Islbutton=props=>{ const[name,setName]=useState; const[isOn,setIsOn]=useStatetrue; //一些功能 回来 切换图像}/> ; } 您需要使用useEffect来处理函数组件中的外部属性更改。参见下面的示例

const{Component,useState,useffect}=React; const{render}=ReactDOM; const Islbutton=props=>{ const{toggleLight}=props; const[name,setName]=useState; const[isOn,setIsOn]=useStatefalse; useEffect=>{ setNameprops.naem; setIsOnprops.isOn; }; 康斯特岛= https://cdg-webhosting.com/wp-content/uploads/2011/02/help-hint-icon.png; 康斯特伊斯洛夫= https://i.ya-webdesign.com/images/light-bulb-on-off-png-16.vnd; //一些功能 回来 ; }; 类应用程序扩展组件{ 状态={ 灯光:[ {name:light1,isOn:true}, {name:light2,isOn:false}, {name:light3,isOn:false}, {name:light4,isOn:true}, {name:light5,isOn:true} ] }; 构造器{ 超级作物; } toggleLight=灯光=>{ 返回=>{ this.setStateprevState=>{ 灯光:prevState.lights.map_light=>{ 返回灯===灯 ? { 光 伊森:光,伊森 } :_光; } }; }; }; 渲染{ const{lights}=this.state; 回来 {lights.maplight=> } ; } } render,document.querySelectorroot; img{ 宽度:50px; 高度:自动; }
不要使isOn成为状态的一部分,而是将其作为prop传递,就像您在问题中所做的那样:{this.state.buttons.mapbtnada=>}但永远不要在渲染函数中进行API调用。将其移动到componentDidMount,并将结果存储在初始化为[]的状态变量中。我将downLayout作为父组件,然后>包装组件的MachineWrapper,然后>Islbutton。这不是个问题吗?我也想传递所有5个组件的数据,根据你回答的第二部分,是的,它只是用于测试,没有太多地集成到代码中。这会是一个问题吗?不要在render中调用API,即使是为了测试。下面的示例代码包括在父级中处理单击:非常感谢!