因此,我编写了此程序,您可以在其中键入搜索栏,并且显示的选项是API中的设备。当您单击设备时,它将被添加到“购物车”中,并且还可以通过在购物车中单击该项目来删除该项目。我知道我应该使用localStorage来将这些设备保存到当前的浏览器会话中,但是我之前从未使用过localStorage,而且不确定如何将其集成到我已经编写的代码中。有什么想法吗?
class App extends React.Component {
state = {
search: "",
devices: [],
bag: []
};
addDevice = (e, deviceTitle) => {
const array = Array.from(this.state.bag);
if (array.indexOf(deviceTitle) === -1) { //if item has not already been clicked
array.push(deviceTitle);
} else {
return;
}
this.setState({
bag: array
});
};
removeDevice = (e, deviceTitle) => {
this.setState(prevState => ({
bag: prevState.bag.filter(d => d !== deviceTitle)
}));
};
removeAll = e => {
this.setState({
bag: []
});
};
onChange = e => {
const { value } = e.target;
this.setState({
search: value
});
this.search(value);
};
search = search => {
const url = `https://www.ifixit.com/api/2.0/suggest/${search}?doctypes=device`;
fetch(url)
.then(results => results.json())
.then(data => {
this.setState({ devices: data.results });
});
};
componentDidMount() {
this.search("");
}
render() {
return (
<div>
<form>
<input
type="text"
placeholder="Search for devices..."
onChange={this.onChange}
/>
{this.state.devices.map(device => (
<ul key={device.title}>
<p>
{device.title}{" "}
<i
className="fas fa-plus"
style={{ cursor: "pointer", color: "green" }}
onClick={e => this.addDevice(e, device.title)}
/>
</p>
</ul>
))}
</form>
{this.state.bag.map(device => (
<p key={device.title}>
{device}
<i
className="fas fa-times"
style={{ cursor: "pointer", color: "red" }}
onClick={e => this.removeDevice(e, device)}
/>
</p>
))}
<button onClick={e => this.removeAll(e)}>Remove all</button>
</div>
);
}
}
答案 0 :(得分:0)
您的代码正在执行您想要实现的目标。为什么要集成本地存储?我能弄清的唯一原因是刷新页面后保留购物车。
本地存储将数据保存为纯字符串,以便保存数组,您可以按以下方式进行操作
const array = {"devices": [{name: 1}, {name: 2}]};
localStorage.setItem('devices', JSON.stringify(array));
// and to get this item
let devicesFromStorage = localStorage.getItem('devices');
devicesFromStorage = JSON.parse(devicesFromStorage).devices;
在您的组件中
search = search => {
const url = `https://www.ifixit.com/api/2.0/suggest/${search}?doctypes=device`;
fetch(url)
.then(results => results.json())
.then(data => {
this.setState({ devices: data.results });
localStorage.setItem('devices', JSON.stringify({ devices: data.results }));
});
};
您可以在https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
上了解有关本地存储的更多信息。希望它会为您提供帮助。
答案 1 :(得分:0)
:-)嗨艾米丽!
实际上,您可以使用简单的JavaScript存储对象方法,尤其是在这里使用localSession对象。
方法:
对象必须是本地存储中的String对象。这就是为什么sarabs3在存储它之前使用JSON.stringify方法将其转换为字符串。
希望这会有所帮助!