【问题标题】:How to navigate to new page after calling dispatch调用调度后如何导航到新页面
【发布时间】:2019-06-09 03:14:19
【问题描述】:

我无法使用 react 和 redux 正确导航页面。我有一个带有链接按钮的组件。单击按钮时,我需要调用调度来更新我的状态,然后重定向到另一个页面。但是,重定向没有发生可能是因为我的动作创建器中的语法不正确。

如下所示,组件 AI 曾尝试使用组件 A 中的 history.push 导航到下一页。这很有效,但是当我导航回组件时,它似乎两次加载仪表板页面并且出现更多问题A 它没有重新绑定,所以它似乎没有更新为最新状态。通过实际单击包含组件的页面导航栏上的链接来完成导航。

我尝试在组件 A 中使用 ComponentWillMount 和 ComponentWillReceiveNextProps,但这会导致无限循环。

历史助手

import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

组件 A:

import { dataActions } from '../../_actions';

componentDidMount() {
    this.fetchData();
}

handleLoadData(dataId) {
        this.props.dispatch(dataActions.loadData(dataID));
        //history.push('/dashboard')
    }

fetchData() {
    this.props.dispatch(dataActions.getAll());
}

render() {
    console.log("the value of props in render", this.props)
    const { dataList } = this.props; 

    return (
        <div>
            <h1>Data List</h1>
            {(dataList.items) ? renderdataListTable(dataList.items, this): null}
        </div>
    );
}

上面的renderdataListTable 只是返回一个带有按钮链接的简单表格:

&lt;td&gt;&lt;button type="button" class="btn btn-link" onClick={(e) =&gt; self.handleLoadData(data.dataId)}&gt;{data.dataName}&lt;/button&gt;&lt;/td&gt;

动作创建者:

import { history } from '../_helpers';

    function loadData(dataId) {
        return dispatch => {
            dispatch(request(dataId));

                dataService.loadById(dataId)


                .then(
                    dataItems=> {
                        dispatch(success(dataId));
                        history.push('/dashboard');
                    },
                    error => {
                        dispatch(failure(error));
                        dispatch(alertActions.error(error));
                    }
                );
        };

        function request() { return { type: dataConstants.LOADBYID_REQUEST } }
        function success(dataItems, dataId) {
            return { type: dataConstants.LOADBYID_SUCCESS, payload: { dataItems, dataId} }}
        function failure(error) { return { type: dataConstants.LOADBYID_FAILURE, error}}
}

这是我的应用程序组件,其中包含路由器设置:

import { history } from './_helpers';
import { alertActions } from './_actions';
import { PrivateRoute } from './_components';

class App extends React.Component {
    constructor(props) {
        super(props);

        const { dispatch } = this.props;
        history.listen((location, action) => {
            // clear alert on location change
            dispatch(alertActions.clear());
        });
    }


 render() {
        const { alert } = this.props;
        return (
                <Router history={history}>
                <Layout>
                    <MuiThemeProvider>
                        {alert.message &&
                            <div className={`alert ${alert.type}`}>{alert.message}</div>
                        }
                        <PrivateRoute exact path="/" component={HomePage} />
                        <PrivateRoute exact path="/showdata" component={ShowDataList} />

                        <Route path="/home" component={Home} />
                        <Route path="/login" component={LoginPage} />
                        <Route path="/register" component={RegisterPage} />
                    </MuiThemeProvider>
                </Layout>
            </Router>
        );
    }
}

function mapStateToProps(state) {
    const { alert } = state;
    return {
        alert
    };
}

【问题讨论】:

  • 我通常做的是在成功获取数据后在我的 redux 状态中设置一个成功标志,并检查映射到 props 状态成功标志值的componentDidUpdate。如果更改并成功,则调度操作以清除标志并将历史推送到新路由。
  • “console.log(this.props.dispatch(dataActions.loadData(dataID))”的结果是什么
  • 如果承诺this.props.dispatch(dataActions.loadData(dataID)).then(() =&gt; { ... your code })
  • 您是否在您配置路由器的位置添加代码?
  • @Pranay 我添加了配置代码。

标签: reactjs redux


【解决方案1】:

您可以将回调函数作为参数传递给您的操作:

在组件中:

callToFunctionWithCallback(dataId) {
  this.props.loadData(dataId, () => {
    //... here you do your redirect stuff     
  })
}

In Action 创建者:

export const loadData = (dataId, callbackFunction) => {
  // ... do your stuff here
    .then(
      dataItems=> {
         dispatch(success(dataId));
         callbackFunction()
         },
         error => {
           dispatch(failure(error));
           dispatch(alertActions.error(error));
        }
   );

【讨论】:

  • 我试过了,它似乎不起作用。在我触发 handleLoadDate 后,它会导致组件 A 重新呈现。然后 Theis 会导致错误,因为现在 dataList 的状态值不同。
  • 我使用状态来检查页面中要呈现的内容,您可以根据新状态在此处设置重定向或任何其他操作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多