Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

javascript - ReactJS对象过滤器在componentDidMount上未定义(ReactJS object filter get undefined on componentDidMount)

I use map to get data in componentDidMount :(我使用mapcomponentDidMount获取data :)

componentDidMount() { const DistrictOptions = Data.DistrictData.map((obj) => ({ key: obj.id, text: obj.name, value: obj.id, cid: obj.cid })); console.log(DistrictOptions); // return data successfully } And it return data successfully, now I want to do a filter on this object, I treid:(它成功返回了数据,现在我想对此对象做一个过滤器,treid:) const DistrictOptions = Data.DistrictData.filter(x => x.cid === 1).map((v, i) => { return { key: i, value: v.id, text: v.name } }); But this return empty array [] I also tried this:(但这返回空数组[]我也尝试过这个:) const opt = DistrictOptions.find(x => x.cid === 1); But this return undefined , confusing what happen here and what I done wrong.(但是此返回值undefined ,混淆了这里发生的事情和我做错的事情。) this is Data.DistrictData :(这是Data.DistrictData :) const Data = { DistrictData: [{ "id": "1", "name": "ss 1", "cid": "1" }, { "id": "2", "name": "ss 2", "cid": "1" }, { "id": "3", "name": "ss 3", "cid": "1" } ] }   ask by tour travel translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use == comparator for comparing cid as shown or use === operator and convert your cid to number:(您可以使用==比较器比较显示的cid或使用===运算符并将cid转换为数字:)

Using ==(使用==) const DistrictOptions = Data.DistrictData.filter(x => x.cid == 1).map((v, i) => { return { key: i, value: v.id, text: v.name } }); Using ===(使用===) const DistrictOptions = Data.DistrictData.filter(x => Number(x.cid, 10) == 1).map((v, i) => { return { key: i, value: v.id, text: v.name } }); You can also use parseInt(x.cid,10) for a conversion to integer.(您也可以使用parseInt(x.cid,10)转换为整数。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...