【问题标题】:React reload call api function doesn't workReact reload call api函数不起作用
【发布时间】:2020-04-09 07:52:30
【问题描述】:

在一个简单的 react 组件下方加载了一个 twits 列表。 我使用“request-promise”包来获取数据。 第一次调用效果很好(带有钩子效果)。 问题是重新加载功能不起作用。

import React, {useState} from 'react'
import { tw } from './twitProxy'

//tw contains a simple promise request with twitter's api call.

function Twitter(){
    let [twe, setTw] = useState()

    React.useEffect(() => {
        tw.then((data)=>{
            setTw(JSON.parse(data))
        })
    }, [])

    const reloadTwit = () => {
        tw.then((data)=>{
            console.log("reload twit without call api ? ")
            setTw(JSON.parse(data))
        })
    }


    return(
        <div>
            <ul>
                 {
                     (twe !== undefined) ? 
                        twe.map((value, index) => {
                            return <li key={index}>{value.text}</li>
                        })
                        : console.log("loading")

                 }
                 <button onClick={reloadTwit}>Reload Twitter</button>
            </ul>
        </div>
    )
}


export default Twitter

【问题讨论】:

  • 为什么 reloadTwit 是异步的?
  • 我做了一些测试,这里没用。(已删除)
  • 你为什么使用请求承诺包?如果你在前端,你应该使用 fetch。
  • 感谢您的建议,我将切换。

标签: reactjs


【解决方案1】:
function Twitter(){
    let [twe, setTw] = useState()
    let [count, setCount] = useState(0)

    const reloadTwit = () => {
        setCount(count + 1)
    }

  React.useEffect(() => {
        tw.then((data)=>{
            console.log("reload twit without call api ? ")
            setTw(JSON.parse(data))
        })
    }, [count])


    return(
        <div>
            <ul>
                 {
                     (twe !== undefined) ? 
                        twe.map((value, index) => {
                            return <li key={index}>{value.text}</li>
                        })
                        : console.log("loading")

                 }
                 <button onClick={reloadTwit}>Reload Twitter</button>
            </ul>
        </div>
    )
}


export default Twitter

【讨论】:

  • 谢谢你,我会尝试你的解决方案,但我认为我已经做过类似的事情了。
猜你喜欢
  • 2022-01-07
  • 2018-09-04
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
相关资源
最近更新 更多