我正在调用API来获取数据并将其存储在数组中。我还向数组中的每个项目附加了一个新对象,默认布尔值为true。当我单击呈现的数组中的特定元素时,布尔值将更改为false并呈现一个新图标。我已经使用localstorage在页面刷新后保留状态。
我遇到的问题是,当我刷新页面时,我希望API调用更新数组的状态,但我也想保留状态的布尔值我的本地存储..
我现在遇到的问题是,我有一个条件要检查我的componentDidMount()方法中的本地存储,如果不正确,那么将更新数组的整个状态。显然,如果取消此检查,则布尔值的状态将重置为true。
import React from 'react';
import StarBorder from '@material-ui/icons/StarBorder';
import Star from '@material-ui/icons/Star';
import axios from 'axios';
class Test extends React.Component {
constructor(props) {
super(props);
var newData = [];
if (localStorage.getItem('new')) {
newData = JSON.parse(localStorage.getItem('new'));
}
this.state = {
data: newData,
}
}
componentDidMount() {
axios.get('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=true')
.then(res => {
const data = res.data;
if (!localStorage.getItem('new')) {
this.setState({ data: data.map(x => ({...x, starIcon: true}))})
}
})
}
handleClick = (i) => {
this.setState(prevState => ({
data: prevState.data.map((x, key) => (key === i ? {
...x,
starIcon: !x.starIcon
} : x))
}), () => {
localStorage.setItem('new', JSON.stringify(this.state.data));
});
}
render() {
return (
<div>
<table border="1">
<thead>
<tr>
<td>Icon</td>
<td>Name</td>
<td>Price</td>
</tr>
</thead>
<tbody>
{this.state.data.map((n, i) => {
return (
<tr>
<td> <span onClick={() => this.handleClick(i)}> {n.starIcon ? <StarBorder/> : <Star /> } </span> </td>
<td>{n.name}</td>
<td>{n.current_price}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
}
export default Test;
答案 0 :(得分:1)
const fromLocalStorage = localStorage.getItem('new');
if (localStorage.getItem('new')) {
const dataFromLocalStorage = JSON.parse(fromLocalStorage);
this.setState({ data: data.map((x, i) => ({...x, starIcon: dataFromLocalStorage[i].starIcon }) })
} else {
this.setState({ data: data.map(x => ({...x, starIcon: true}))})
}