gpt4 book ai didi

javascript - 使用 onClick 调用相同的函数适用于一件事而不是另一件事?

转载 作者:行者123 更新时间:2023-12-02 23:40:39 26 4
gpt4 key购买 nike

我正在创建一个应用程序,用户可以在其中使用搜索栏搜索设备,或浏览嵌套菜单。当用户找到他们想要的设备时,他们单击绿色加号将其添加到他们的“包”中。由于某种原因,我编写的 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>
)}

这就是从搜索中添加设备时的样子(工作正常) enter image description here

这就是当我尝试从菜单中添加“领带”时发生的情况。之后它不允许我添加任何其他内容

enter image description here

最佳答案

在这一行中onClick={e => this.addDevice(e, this.value)}this 的值指向类本身。因此,this.valueundefined,它不允许您添加更多内容,因为undefined 已经在数组中并且undefined === undefined 实际上是正确的。要解决此问题,您需要传递设备标题的正确值。

关于javascript - 使用 onClick 调用相同的函数适用于一件事而不是另一件事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56095676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com