Estoy usando el componente react-infinite-scroll para implementar el componente de desplazamiento infinito. La configuración del componente es:
<div id="scrollableDiv" style={{ height: 300, overflow: "auto" }}> <InfiniteScroll dataLength={texts.length} next={getText} hasMore={true} loader={<h5>Loading...</h5>} endMessage={<p style={{textAlign:'center'}}><b>Yay! You've seen it all!</b></p>} scrollableTarget="scrollableDiv" > {<Texts texts = {texts}/>} </InfiniteScroll> </div>
donde texts es simplemente una matriz de estado de algunos objetos de texto; const [texts, setTexts] = useState([])
Este es el método getText que se llamará a next
:
const getText = async ()=>{ const res = await axios.get("http://localhost:3001/api/sth",{ params: { ids: followings.map(i => i.id), str_ids: followings.map(i => i.str_id) }, paramsSerializer: params => { return qs.stringify(params) } }); let str_ids_res = res.data.map(i => i.string_id) let texts_res = res.data.map(i => i.texts) console.log(texts_res) const filtered_res = //some processing here on texts_res /* eslint eqeqeq: 0 */ if(!arrayIsEqual(filtered_res,texts)){ console.log("Not equal") // append arrays to a array state setTexts((prevtexts) => prevtexts.concat([...filtered_res])) } }
await axios.get("http://localhost:3001/api/sth")
siempre devuelva dos textos diferentes de DB, por lo que siempre se debe llamar a setTexts
.
componente es un componente de tarjeta de IU semántica aunque.
const Texts = ({texts}) =>{ return ( <> {texts.map(text =>( <div key={text.id}> <Card> <Card.Content> <Card.Description> {text.full_text} </Card.Description> </Card.Content> </Card> </div> ))} </> ); }
El componente InfiniteScroll
solo activa Next
una vez aunque mi variable de datalength
de datos esté configurada correctamente.
PD. el texto está vacío inicialmente, así que cuando inicio la aplicación, solo se llama 'Cargando...'
Después de algunos experimentos, pasar height = {some height}
como apoyos a InfiniteScroll hace el truco...
<div id="scrollableDiv" style={{ height: 300, overflow: "auto" }}> <InfiniteScroll dataLength={tweets.length} next={handleScrolling} hasMore={!isEnd} loader={<h5>Loading...</h5>} scrollThreshold={1} height={300} endMessage={ <p style={{textAlign:'center'}}><b>Yay! You've seen it all!</b></p> } scrollableTarget="scrollableDiv" > {<Tweets tweets = {tweets}/>} </InfiniteScroll> </div>
No inicialice 'textos' con una matriz vacía, debe inicializar la matriz 'textos' con alguna matriz de objetos (por ejemplo, 10 o 20).
En el renderizado inicial de su código (en la primera vez). simplemente puede activar una API en
useEffect(()=>{ // make API call which your firing in the next call function },[])
Entonces, su componente se inicializa y luego comenzará a comportarse como se esperaba.
Para su comprensión, consulte el ejemplo de muestra en "code sandbox"https://codesandbox.io/s/elated-danny-k4hylp?file=/src/index.js