【问题标题】:react router - make an ajax call only once per component反应路由器 - 每个组件只进行一次 ajax 调用
【发布时间】:2017-09-19 11:34:28
【问题描述】:

我的路线设置如下:

<Router>
    <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
    </Switch>
</Router>

在 Home 组件上,我只想在第一次挂载时进行 ajax 调用。

export default class Home extends Component {
    componentDidMount(){
        //make ajax call only once. Do some stuff on .then()
    }
}

问题是如果用户在 Home 和 About 之间切换页面,Home 组件会重新渲染所有内容,因此我的 ajax 调用将再次被触发。

我该如何解决这个问题? 我应该将第一个数据提取存储在 redux 存储中,然后使用 if 语句还是有更好的方法?

【问题讨论】:

  • 你可以缓存数据或者返回一个promise。一旦 promise 得到解决,您将可以访问数据。不需要 IF 语句。
  • 缓存在哪里?在商店里?本地存储?如果可以,请添加示例
  • 我是否应该将第一个数据提取存储在 redux 存储中,然后使用 if 语句 ---> 如果您使用的是 redux,这是最好的方法。
  • @NarasimhaReddy 现在,不,我没有使用它,但即便如此,我仍然需要做一个 IF 语句来检查之前是否提取了数据,对吧?
  • 是的,你需要检查你的redux状态是否有数据。

标签: reactjs react-router


【解决方案1】:

如果你想使用 Redux,如果数据还没有,你需要调度一个操作来获取数据。

class Home extends Component {
    componentDidMount(){
        if (!this.props.homeContent) {
            this.props.dispatch(fetchHomeContent());
        }
    }
}

// Map redux store to your component props
const mapStateToProps = (state) => {
     return {
         'homeContent': state.homeContent
     }
}

// Redux 'connect' function, to subscribe your component for state changes.
export default connect(mapStateToProps)(Home);

你的动作是异步的,所以你应该使用 redux-thunk 中间件,请查看文档了解它的设置。

你的行为:

function fetchHomeContent(subreddit) {
     return dispatch => {
         return fetch(`https://your-domain/pathname`)
             .then(response => response.json())
             .then(json => dispatch(receiveData(json)))
     }
}

function receiveData(json) {
    return {
        type: 'receive',
        data
    }
}

还有你的减速器:

switch (action.type) {
    case 'receive':        
        return Object.assign({}, state, {
            'homeContent': action.data
        })
    default:
        return state
}

这只是为了让您了解您的一般设置,但您仍然需要连接它(设置您的 store、root reducer 等),最好的方法是关注 Redux docs/tutorial

如果您需要对应用的其他部分进行类似的缓存,此解决方案会很好。如果这对您来说开销很大,您可以像上面提到的那样保存在 localStorage 中。并在 componentDidMount 上阅读。

【讨论】:

  • 是的,这对我来说已经足够了。无论如何,我更感兴趣的是我是否还需要使用 IF 语句,所以我会的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
相关资源
最近更新 更多