【发布时间】: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 只是返回一个带有按钮链接的简单表格:
<td><button type="button" class="btn btn-link" onClick={(e) => self.handleLoadData(data.dataId)}>{data.dataName}</button></td>
动作创建者:
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(() => { ... your code }) -
您是否在您配置路由器的位置添加代码?
-
@Pranay 我添加了配置代码。