[英]how to setstate in if react native
您好我正在嘗試將exportTest
導出到另一個 js 文件並重新渲染。 我正在嘗試這樣
import React, { useState } from 'react';
import { StyleSheet, View } from 'react-native';
var n;
export var exportTest;
function foo()
{
//doing something and giving back n as 1 or 0
}
export default function App () {
const [test,setTest] = useState();
if(n == 0)
{
//doing something
setTest('n is zero')
}
else
{
//doing something
setTest('n is not zero')
}
exportTest=test
return(
<View>
...
...
...
</View>
);
}
我在too meny re-renders
時遇到錯誤,因為我在 if 中執行setTest
如何在if
的最后一行if
setTest
一次? n
在某些 function 中發生變化,我將其設為 1 或 0。這就是我在另一個文件中導入exportTest
的import {exportTest} from './App.js';
import React, { useState } from 'react';
import { StyleSheet, TouchableOpacity, View, Text } from 'react-native';
export const exportTest = () => {
const [test,setTest] = useState();
let n = 0;
if(n == 0)
{
setTest('n is zero')
}
else
{
setTest('n is not zero')
}
exportTest=test
return(
...
...
...
);
}
試試看。 您將其作為 const 導入,因此您編寫了 {exportTest} 導入。 您需要將 exportTest 導出為 const。
有很多事情錯了,您刪除了退貨,因此您的目的不明確。 看看是否有幫助。 隨時再次發表評論。 我建議清理你的代碼。
您正在創建一個無限循環。 State 和道具更改觸發重新渲染,在您的情況下 - 重新渲染觸發 state 更新。 這就是為什么 state 更新不應該成為渲染器邏輯的一部分。
來自 reactjs.org:
setState 是做什么的?
setState() 計划對組件的 state object 進行更新。 當 state 發生變化時,組件通過重新渲染來響應
通常,您會在componentDidMount
或componentWillReceiveProps
上執行所有 state 操作,而 hook 的替代方法是Effect Hook
。
useEffect(() => {
// componentWillMount
return () => {
// componentWillUnmount
};
});
觸發道具更新:
useEffect(() => {
// prop abc changed
}, [props.abc]);
請注意,在后一個示例中,我省略了 return 語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.