我正在尝试在我的本机应用程序中使用状态挂钩。但是没有调用set state方法,我的状态值正在更新
export default function Interface(){
const [requireddata,setrequireddata]= useState({vehiclesfulldata:[]});
const [requireddataflag,setrequireddataflag]=useState(true);
useEffect(()=>{
const interfacedata= async function fetchinterfacedata() {
const resultdata= await Fetchdata(postdata).then(async(response) => {
let responsedata=JSON.parse(response);
return responsedata
})
setrequireddata({...requireddata, vehiclesfulldata:JSON.parse(resultdata.fullvehicledata)});
}
interfacedata();
},[requireddataflag])
const fleetsearchdata=(searchdata)=>{
let fleetdetails=requireddata.vehiclesfulldata;
if(searchdata!=""){
searchdata=searchdata.toLowerCase();
fleetdetails.forEach((g)=> {
g.fleets.forEach((s)=> {
s.fleets = s.fleets.filter(f => f.name.toLowerCase().indexOf(searchdata) > -1);
})
})
}
console.log(fleetdetails);
console.log(requireddata.vehiclesfulldata);
// console.log(fleetdetails);
}
return (
<SafeAreaView style={{flex: 1}}>
<View style={[Interfacestyle.fleetsearchview]}>
<Input
placeholder='Search Fleet'
onChangeText={(value)=>{fleetsearchdata(value)}}
inputContainerStyle={Interfacestyle.inputcontainerfleetsearch}
containerStyle={Interfacestyle.inputfleetsearch}
style={Interfacestyle.fleetsearch}
rightIcon={{ type: 'font-awesome', name: 'search' ,color:'#C9C9C9',size:17,solid:'true'}}
rightIconContainerStyle={Interfacestyle.fleetsearchIcon}
/>
</View>
</SafeAreaView>
)
}
以上是我的代码。最初我使用 fetch api 获取数据,结果为
Array [
Object {
"GroupId": 1,
"fleets": Array [
Object {
"GroupId": 1,
"StationId": null,
"fleets": Array [
Object {
"GroupId": 1,
"StationId": null,
"fleetId": 316,
"name": "TM-175 PLATE-286398",
},
],
"name": "General",
},
],
"name": "TRUCK MIXER",
},
]
调用fleetsearchdata函数时,requireddata中的状态值正在更新,没有调用 setrequireddata 函数。
请帮助我。
答案 0 :(得分:0)
问题在于,在您的 fleetsearchdata
函数中,您将状态分配给一个变量 (fleetdetails=requireddata.vehiclesfulldata
),在这种情况下,对 fleetdetails
的任何更改都将对原始变量进行,因为你不是在复印,而是在做作业。所以你必须制作一个副本,然后进行过滤。您可以在此处找到更多信息:https://javascript.plainenglish.io/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089
我建议使用 lodash 的 _.cloneDeep