我有一个数据数组,我正在映射到一个材料-ui排版。
{
array.map((item, id)=> <Typography key={id} value={item.name} />)
}代码按照预期在浏览器上显示排版及其各自的值,但是,我试图将排版的映射值设置为这样的状态.
const [data, setData] = useState();..。
{
array.map((item, id) =>
<Typography key={id} value={item.name} {(e)=>setData(e.target.value)} />
)}此方法不起作用。如何使data成为<Typography/>的值
发布于 2021-10-19 15:56:28
如果我理解正确的话,您是想在本地州内存储item.name吗?如何接收正在映射的数据?
您是否试图存储正在映射的每个项,并表示本地状态中对象的键值对?一旦你拥有了这个国家,你想要做什么?
据我所知,在通过数组进行映射时,无法将值赋值给本地状态。但是,有多种方法可以将数据分配给返回之外的本地状态。
还有,这条线在做什么?
{(e)=>setData(e.target.value)}似乎您正在尝试在没有onChange支柱的排版组件上创建受控输入,以及在不接受输入的组件上创建受控输入。
再说一句,虽然没什么大不了的-
{
array.map((item, id) =>
<Typography key={id} value={item.name} ..../>
)}这里的id通常称为索引。
编辑的答案
我通常使用Redux来管理全局状态,但是对于上下文提供程序来说,流程应该是相同的:
const yourComponent = () => {
const [data, setData] = useState();
// This is the array you get from the Context Provider
const yourArray = getArrayFromContextProvider();
useEffect(() => {
// If you want to normalize the array data
if (yourArray) {
const dataObj = {};
yourArray.forEach((item, index) => {
// Make the key unique by using the item id OR you can use index
dataObj[item.id] = item;
// OR you can add the item value as the key
dataObj[item.value] = item;
});
setData(dataObj);
}
// If you just want to store the array
if (yourArray) {
setData(yourArray)
}
}, [yourArray]);
return <div>
{/* ...Your map */}
</div>;
};
export default yourComponenthttps://stackoverflow.com/questions/69633920
复制相似问题