reactjs - 为什么 React Component 渲染两次
问题描述
我有这个代码:
const fetchRequest = useCallback( () => {
setIsLoading( true );
axios( {
method: "GET",
url: "https://bouvet.guru/rekrytering_flera.php"
} ).then( ( response ) => {
if ( response.data.indexOf( "https://" ) !== -1 ) {
let splittedArray = response.data.split( "Data:" );
let dataString = splittedArray[1];
if ( dataString.includes( "<URL kommentar>" ) ) {
dataString.substring( 16 );
let pairedData = dataString.split( "http" );
pairedData.splice( 0, 1 );
const finalArray = pairedData.map( ( group ) => {
const url = group.split( " " )[0];
const comment = group.replace( url, "" );
// Return an object with the paired properties. ID is not optimal to be Math.random(), this is for demonstration purpose.
return { url: "http" + url, comment, id: Math.random() };
} );
setData( [ ...data, ...finalArray ] );
setIsLoading( false );
} else {
console.log( "NOPE" );
}
} else {
console.log( "We could not find any data" );
setIsLoading( false );
}
} );
}, [] );
useEffect( () => {
fetchRequest();
setInterval( () => {
fetchRequest();
}, 30000 );
}, [] );
console.log( data );
这只是一个简单的 useEffect axios 调用,我在其中收到一个字符串,然后将其设置为状态,然后将其记录到控制台。
我总是得到 2 个相同的数组。
(我现在知道它是一个 useCallback,但是当它只是整个代码中的一个 useEffect 时遇到了同样的问题。
该组件是独立的。
解决方案
你可以做:
const fetchRequest = () => {
setIsLoading( true );
axios( {
method: "GET",
url: "https://bouvet.guru/rekrytering_flera.php"
} ).then( ( response ) => {
if ( response.data.indexOf( "https://" ) !== -1 ) {
let splittedArray = response.data.split( "Data:" );
let dataString = splittedArray[1];
if ( dataString.includes( "<URL kommentar>" ) ) {
dataString.substring( 16 );
let pairedData = dataString.split( "http" );
pairedData.splice( 0, 1 );
const finalArray = pairedData.map( ( group ) => {
const url = group.split( " " )[0];
const comment = group.replace( url, "" );
// Return an object with the paired properties. ID is not optimal to be Math.random(), this is for demonstration purpose.
return { url: "http" + url, comment, id: Math.random() };
} );
setData( [ ...data, ...finalArray ] );
setIsLoading( false );
} else {
console.log( "NOPE" );
}
} else {
console.log( "We could not find any data" );
setIsLoading( false );
}
} );
};
useEffect( () => {
fetchRequest();
const interval = setInterval( () => {
fetchRequest();
}, 30000 );
return ()=>{clearInterval(interval);}
}, [] );
console.log( data );
推荐阅读
- autodesk-forge - 在 Autodesk Forge 查看器中选择多个对象
- javascript - Firebase 实时数据库 - 额外数据节点的最佳实践(查找和初始加载)
- excel - 如何使用 VBA 代码 Excel 进行代码循环,直到另一个工作簿中的最后一张工作表?
- node.js - 检查 NODE_ENV 是否会不必要地减慢我们在生产中的 Express 应用程序?
- java - Java:如何读取带有日期作为名称一部分的文件
- laravel - Laravel 有查询
- vhdl - 使用 FIFO 的 VHDL 中的 FPGA 到 HPS 通信
- java - 在 Android studio 中,在我的应用程序中,图像没有被位图替换
- r - 如何使用 cmd 预处理整数值上的 .csv 文件并从 data.table 中读取
- php - 如何在 symfony 5 中使用 mysql 而不是 mariadb