【问题标题】:React native setState value before fetch在获取之前反应原生 setState 值
【发布时间】:2021-01-30 13:01:01
【问题描述】:

在 react native 代码中,例如我有一个 2 状态。

const [data, setData] = useState([]);
const [page, setPage] = useState(0);

调用函数时,即搜索函数

search = async() => {
    setData([]);
    setPage(0);
    console.log("Page: " + page); // This will return 0 because of the setPage(0) above, or can call setPage((state)) to wait until page set to 0
}

如果多次调用上述搜索功能,则页面为0。是预期的。

但如果这段代码继续,

search = async() => {
    setData([]);
    setPage(0);
    console.log("Page: " + page); // This page will be always increment because fetch then setPage+1 above
    fetch(url)
       .then((response) => response.json())
       .then((json) => { setData(data.concat(json.content)); setPage(page+1); })
       .catch((error) => console.error(error))
       .finally(() => { });
}

日志将是

Page: 1
Page: 2
Page: 3

预期应该始终是 Page: 0

问题是,如何设置页面为0,然后获取url,所以在获取之前的值始终为0。目的很简单,当这个搜索功能触发时,页面必须为0,然后再次获取数据。

【问题讨论】:

    标签: react-native state use-state


    【解决方案1】:

    由于您总是希望您的页面在 fetch 之前始终为 0,这意味着 setPage(page+1); 应该使 page 1 ,那么您可以执行以下操作:

    search = async() => {
        setData([]);
        fetch(url)
           .then((response) => response.json())
           .then((json) => { setData(data.concat(json.content)); setPage(1); })
           .catch((error) => console.error(error))
           .finally(() => { });
    }
    

    直接将页面指定为1,而不是执行page+1编辑

    const[start,setStart]=useState(false);
    
    useEffect(()=>{
    if(start){
    setPage(0);
    setData([]);
    }
    },[start])
    
    search = async() => {
        setStart(true);
        console.log("Page: " + page); // This page will be always increment because fetch then setPage+1 above
        fetch(url)
           .then((response) => response.json())
           .then((json) => { setData(data.concat(json.content)); setPage(page+1); })
           .catch((error) => console.error(error))
           .finally(() => { });
        setStart(false);
    
    }
    

    【讨论】:

    • 那么分页呢?该搜索功能实际上是将分页的页面重置为0。将加载更多,页面将始终递增,即,1,2,3等......我问这更多的是概念异步和承诺返回的状态。但是如果和fetch结合使用,在触发fetch之前不能先设置值...
    • 不能,值还是会递增
    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 2019-06-10
    • 2017-01-13
    • 2015-12-31
    • 2020-05-06
    • 2019-01-08
    • 1970-01-01
    相关资源
    最近更新 更多