如何在React钩子动态路由中获取数据?

时间:2020-09-01 11:09:11

标签: reactjs redux react-redux react-router react-hooks

我正在编写简单的博客集。我有最新的react-router和react-redux。我的商店里有所有博客。当我导航到单个博客页面时,它第一次运行良好,但是当我刷新浏览器或直接向地址栏输入动态url时,组件的数据松散。我应该使用哪种挂钩来获取数据?我的SingleBlog中只有这个来获取数据:

function filter_woocommerce_package_rates( $rates, $package ) { 
    // Get cart contents weight
    $weight = WC()->cart->get_cart_contents_weight();
 
    // Conditions
    if ( $weight <= 24 ) {
        // Set available shipping options
        $available_shipping = array( 'local_pickup' );
    } elseif ( $weight > 24 || $weight < 50 ) {
        $available_shipping = array( 'local_pickup', 'flat_rate' );
    } else {
        $available_shipping = array( 'local_pickup', 'free_shipping' );
    }
    
    foreach ( $rates as $rate_key => $rate ) {
        // Targeting, NOT in array
        if ( ! in_array( $rate->method_id, $available_shipping ) ) {
            unset( $rates[$rate_key] );
        }
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

1 个答案:

答案 0 :(得分:0)

刷新浏览器时,整个应用程序将重新启动,其中包括保存数据的状态。

如果即使在刷新浏览器后仍要保留数据,则应将数据保存在localStorage中并修改代码,以便它从保存在localStorage中的数据中获取状态。

您该怎么做:
获取数据时

...
// Where data is the variable that holds your fetched data
localStorage.setItem('data_array', JSON.stringify(data));

在Blog reducer中

...
// Instead of having the initial state as empty array `[]`, you make it equal
// to whichever data is stored in the localStorage. Because if the localStorage
// have no data, it will still return an empty array `[]`
const initialState = JSON.parse(localStorage.getItem('data_array'));

export function blogReducer(state = initialState, action) {
  switch (action.type)
  ...
}

在博客页面中

...
// You keep blog const as it is since we took care of the localStorage in
// the reducer
const blog = useSelector(state => state.blogs.find(b => b.id === id))
...

快速注释:
您不应该依赖刷新浏览器来获取新的博客文章/数据。但是,您可以使用setInterval()每隔x次发送获取请求,以查看是否有任何新的帖子/数据,或者您可以在应用中添加刷新按钮,以触发获取请求的请求任何新数据