我正在创建一个应用程序,用户可以在其中搜索带有搜索栏的设备,或浏览嵌套菜单。当用户找到他们想要的设备时,他们点击绿色加号将其添加到他们的“包”中。出于某种原因,addDevice
我编写的函数仅适用于搜索功能,而不适用于在菜单中调用时。它似乎部分工作,但不正确。有谁知道我的代码中的什么可能导致这种情况?请参阅下面的图片了解更多详情。
我还进行了两种不同的 API 调用,一种用于搜索栏(在其自己的函数中调用),另一种用于菜单(在 中调用componentDidMount
)。这可能是导致错误的原因吗?
我不会包括每一行代码,因为它很多,但是如果您想查看其他代码,请告诉我。
class App extends React.Component {
state = {
devices: [],
bag: [],
objectKeys: null,
tempKeys: []
};
这是由 onClick 调用的函数
addDevice = (e, deviceTitle) => {
const array = Array.from(this.state.bag || []);
if (array.indexOf(deviceTitle) === -1) {
array.push(deviceTitle);
} else {
return;
}
localStorage.setItem("list", JSON.stringify(array));
this.setState({
bag: array
});
};
这是调用 addDevice 时似乎不起作用的函数
makeMenuLayer = layer => {
const { objectKeys } = this.state;
if (layer == null) {
return null;
}
const layerKeys = Object.entries(layer).map(([key, value]) => {
{/*If value has children, display an arrow, if not, do nothing*/}
var arrow = Object.keys(value).length ? (
<i
className="fas fa-angle-right"
style={{ cursor: "pointer", color: "gray" }}
/>
) : (
""
);
{/*If value has no children, display an plus sign, if not, do nothing*/}
var plus =
Object.keys(value).length === 0 ? (
<i
className="fas fa-plus"
style={{ cursor: "pointer", color: "green" }}
onClick={e => this.addDevice(e, this.value)}
/>
) : (
""
);
return (
<ul key={key}>
<div onClick={() => this.handleShowMore(key)}>
{key} {arrow} {plus}
</div>
{objectKeys[key] && this.makeMenuLayer(value)}
</ul>
);
});
return <div>{layerKeys}</div>;
};
这是调用执行工作的 addDevice 的地方
render () {
return(
<div className="search-results">
{(this.state.devices || []).map(device => (
<a key={device.title}>
<li>
{device.title}{" "}
<i
className="fas fa-plus plus input"
style={{ cursor: "pointer", color: "green" }}
onClick={e => this.addDevice(e, device.title)}
/>
</li>
</a>
))}
</div>
)}
当我尝试从菜单中添加“领带”时会发生这种情况。之后它不允许我添加任何其他内容
在这一行中onClick={e => this.addDevice(e, this.value)}
的值this
指向类本身。因此,this.value
is undefined
,它不允许您添加更多内容,因为undefined
它已经在数组中并且undefined === undefined
实际上是真的。要解决此问题,您需要传递设备标题的正确值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句