在React Router

时间:2017-12-03 12:12:41

标签: reactjs react-router-v4

我有一个函数来构造一个像这样的查询字符串:

search = (params) => {
    for (let key in params) {
        if (params[key] === '') delete params[key];
    }
    params = CaseConverter.camelCaseToSnackCase(params);
    let paramString = queryString.stringify(params);
    paramString = '?' + paramString;
    this.props.history.push(paramString);
    this.callAPI();
}

这是callAPI函数:

callAPI = () => {
    get('/endpoint' + this.props.location.search).then(response => {});
}

但是,this.props.location.search在第一次通话时不会更新。我总是要打两次search才能得到我想要的东西。有谁知道解决这个问题?

注意:我正在使用reactreact-router-dom v4,query-string

1 个答案:

答案 0 :(得分:0)

您只会在下次重新渲染时看到更新的道具。为什么不将查询直接传递给callAPI函数,如下所示:

search = (params) => {
    for (let key in params) {
        if (params[key] === '') delete params[key];
    }
    params = CaseConverter.camelCaseToSnackCase(params);
    let paramString = queryString.stringify(params);
    paramString = '?' + paramString;
    this.props.history.push(paramString);
    this.callAPI(paramString);
}

callAPI = (q) => {
    get('/endpoint' + q).then(response => {});
}