我有一个问题,我会在登录后将用户发送到react-router路由,具体如下:
...
//check login
browserHistory.push(self.props.destination_url);
我期待componentDidMount
能够运行,因为自从我加载应用程序以来,该组件并未出现在屏幕上,但它不会。如果我在导航栏中单击指向它的链接(react-router链接),则componentDidMount
会运行。
由于browserHistory.push(self.props.destination_url);
路由更改,我只需要在屏幕上显示此组件时进行API调用。我尝试过像
<Router createElement={ (component, props) =>
{
const { location } = props
const key = `${location.pathname}${location.search}`
props = { ...props, key }
return React.createElement(component, props)
} }/>
此处Component does not remount when route parameters change并且它无法正常工作。
此处http://busypeoples.github.io/post/react-component-lifecycle/显示&#34; on&#34;,&#34; on unmount&#34;,&#34; on state change&#34;,或&#34; on props changes&# 34 ;.我没有看到任何适用于此的内容。是否存在将在此browserHistory推送转换后运行的生命周期方法?
我一直尝试使用随机生命周期方法,componentWillUpdate
确实在browserHistory.push
之后运行,但它运行了数百次,完全减慢了应用程序的速度。我假设我在里面做的事情导致了几乎无限的循环:
componentWillUpdate() {
console.log('it ran componentWillUpdate');
if (this.props.email) {
console.log('firing off /api/userInfo');
let self = this;
axios.post('/api/userInfo', {email: this.props.email})
.then(function (response) {
let result = response.data.result;
console.log('after calling /api/userInfo');
console.log(response);
console.log(result);
if (result) {
self.setState({restaurant_profile: result});
}
})
.catch(function (error) {
console.log("Something went wrong trying to check for a user's restaurant profile");
console.log(error);
});
}
}
在服务器/客户端上,您现在看到POST运行了数百次:
Executing (default): SELECT `id`, `email`, `password`, `RestaurantId` FROM `Users` AS `User` WHERE `User`.`email` = 'fake@fake.com' LIMIT 1;
Executing (default): SELECT `id`, `email`, `password`, `RestaurantId` FROM `Users` AS `User` WHERE `User`.`email` = 'fake@fake.com' LIMIT 1;
Executing (default): SELECT `id`, `email`, `password`, `RestaurantId` FROM `Users` AS `User` WHERE `User`.`email` = 'fake@fake.com' LIMIT 1;
Executing (default): SELECT `id`, `email`, `password`, `RestaurantId` FROM `Users` AS `User` WHERE `User`.`email` = 'fake@fake.com' LIMIT 1;
...
这适用于学生的演示,但不适用于长期演示。寻找一个只运行一次的生命周期方法,并且改变状态是安全的并且不会导致无限循环
我的r
个依赖关系看起来像
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-redux": "^5.0.6",
"react-router": "^3.0.5",
"react-router-dom": "^4.2.2",
"react-transform-hmr": "^1.0.4",
"redux": "^3.7.2",
这些路线看起来像
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import { Router, Route, Link, IndexRoute, browserHistory } from "react-router";
import reducers from "./reducers";
import { loadConfig, getConfig } from "./config";
import Nav from "./Nav";
import LoginPage from "./containers/LoginPage";
import MapShowRestaurants from "./components/MapShowRestaurants";
import RestaurantRegistration from "./containers/RestaurantRegistration";
const createStoreWithMiddleware = applyMiddleware()(createStore);
getConfig.then((config) => {
loadConfig(config);
ReactDOM.render(
(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory}>
<Route path="/" component={Nav}>
<IndexRoute component={MapShowRestaurants} />
<Route path="/login" component={LoginPage} />
<Route path="/registerRestaurant" component={RestaurantRegistration} />
</Route>
</Router>
</Provider>
), document.querySelector('.container'));
})
.catch((err) => {
console.log(err);
})
答案 0 :(得分:4)
不要在组件生命周期中放置API调用。
制作动作
function getUserInfo(payload) {
// do axios
return {
type: 'GET_USER_INFO',
payload: result_of_your_api_call,
error: false/true
};
}
为此操作创建reducer并在reducer中改变状态
之后,你需要matStateToProps和mapDispatchToProps
connect(mapStateToProps, mapDispatchToProps)(YourMagicComponent)
连接您的组件和您的redux
之后,您将在组件中获得redux状态。有关详细信息,请阅读此http://redux.js.org/docs/basics/ExampleTodoList.html
记住 1.当组件初始化时,除了defaultProps之外,它在props中没有任何数据。 2. componentDidMount不知道组件外的任何东西(仅在组件安装之前定义的默认道具和道具) 3.如果您需要在componentWillUpdate中执行某些操作,则需要定义更新组件的规则
componentWillUpdate(nextProps) {
this.setState(key: nextProps.key)
}
shouldComponentUpdate(nextProps, nextState) {
// fix for your update
if (this.state.key !== nextProps.key) {
return true;
}
}
答案 1 :(得分:2)
@ codyc4321尝试 self.props.router.push('/ url')