我有JSON
请求调用了fetch()
:
[{
"name": "",
"value": "1"
},
{
"name": "",
"value": "3"
},
{
"name": "",
"value": "2"
},
{
"name": "",
"value": "4"
},
{
"name": "",
"value": "4"
},
{
"name": "",
"value": "5"
},
{
"name": "",
"value": "2"
},
{
"name": "",
"value": "5"
}]
我想根据名为value
的文件过滤数据。 value
将是一个数字,例如1
或一些用逗号1,5,4
分隔的数字。我想说的是过滤数据{item.value}
所包含的内容value
value
为空时,向我显示所有数据。我这样写:
library = library.filter(item =>
item.value==Filtervalue
)
但是它仅在我在value
:1
中有一个数字并且对逗号1,5,4
分隔的某些数字不起作用时才过滤数据。
这是我的一部分代码:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
library: null,
Filtervalue: "",
}
}
componentDidMount() {
fetch('/json.bc', {
method: 'POST',
})
.then(response => response.text())
.then(text => {
const Maindata = JSON.parse(text.replace(/\'/g, '"'))
this.setState(state => ({
...state,
data: Maindata
}), () => {
this.reorganiseLibrary()
})
}).catch(error => console.error(error))
})
}
reorganiseLibrary = () => {
const { Filtervalue} = this.state;
let library = data;
if (Filtervalue !== "") {
library = library.filter(item =>
item.value==Filtervalue
)
}
library = _.chunk(library);
this.setState({
library
})
}
handlerFilter = evt =>
this.setState(
{
Filtervalue: evt.target.value
},
() => {
this.reorganiseLibrary();
}
)
renderLibrary = () => {
const { library} = this.state;
if (!library || (library && library.length === 0)) {
return <div>nodata</div>
}
return library.map((item, i) => (
<div>
<span>{item.realname}</span>
<span>{item.value}</span>
</div>
))
}
render() {
const { library} = this.state;
return (
<div>
{this.renderLibrary()}
<input value={this.state.Filtervalue} onChange={this.handlerFilter} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('Result'))