[英]Using axios doesn't rerender my React Native component
I am using hooks in React Native.我在 React Native 中使用钩子。 This is my code:
这是我的代码:
useEffect(() => {
if (var1.length > 0 ){
let sym = [];
var1.map((items) => {
let count = 0;
state.map((stateItems) => {
if(items === stateItems.name) {
count = count + 1;
}
})
if (count === 0) {
sym.push(items)
}
});
async function getAllStates (sym) {
let stateValues = [];
await Promise.all(sym.map(obj =>
axios.get(ServerURL + "/note?name=" + obj).then(response => {
stateValues.push(response.data[0]);
})
)).then(() =>{
setNewItem(stateValues);
});
}
getAllStates (sym);
}
}, [var1]);
useEffect(() => {
let stateValues = state;
for( let count = 0 ; count < newItem.length; count++ ){
stateValues.push(newItem[count]);
}
setState(stateValues);
}, [newItem]);
This runs successfully without any errors.这成功运行,没有任何错误。 However, when the state is displayed as below, I am not seeing the latest value added in the state. It shows all the previous values.
但是,当 state 显示如下时,我没有看到 state 中添加的最新值。它显示了所有以前的值。 When I refresh the whole application, I am able to see my value added.
当我刷新整个应用程序时,我能够看到我的附加值。
return (
<View style={styles.container}>
<Text style = {{color:"white"}}>
{
state.map( (item, key) =>{
return(
<Text key = {key} style = {{color:"white"}}> {item.name} </Text>
)
})
}
</Text>
</View>
);
Can someone tell me why this is happening?有人能告诉我为什么会这样吗? I want to see the data render immediately after the axios call.
我想在 axios 调用后立即看到数据呈现。 I am using React Native.
我正在使用 React Native。
when i force update using: stackoverflow.com/questions/53215285/... it works fine.
当我强制更新时使用: stackoverflow.com/questions/53215285/...它工作正常。 However, i am looking for a better fix if anyone can provide?
但是,如果有人可以提供,我正在寻找更好的解决方案?
This should do:这应该做:
useEffect(() => {
var1.forEach(async (name) => {
if (state.some(item => item.name === name)) return;
const response = await axios.get(ServerURL + "/note?name=" + name);
setState(state => [...state, response.data[0]]);
});
}, [var1]);
I still see two issues in your approach:我仍然在您的方法中看到两个问题:
this code may start the same ajax request multiple times before the result of the firstz ajax-request is added to state
;在将第一个 ajax 请求的结果添加到
state
之前,此代码可能会多次启动相同的 ajax 请求; this also means that the result for the same name
may be added multiple times to state
.这也意味着相同
name
的结果可能会多次添加到state
中。
for each item of var1 times each item of state, this is an O(n*m)
problem or in this case basically O(n²)
as m
is pretty fast catching up to n
.对于 var1 的每一项乘以 state 的每一项,这是一个
O(n*m)
问题,或者在这种情况下基本上是O(n²)
,因为m
很快赶上n
。 You should find a better approach here.你应该在这里找到更好的方法。
And I'm almost certain that [var1]
is wrong here as the dependency for useEffect
.而且我几乎可以肯定
[var1]
在这里作为useEffect
的依赖项是错误的。 But you'd need to show where this value comes from to fix that, too.但是您也需要显示此值的来源才能解决该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.