我出现了以下错误:
警告:setState(...):不能在现有状态转换期间更新(例如在render或另一个组件的构造函数中)。Render方法应该是props和state的纯函数;构造函数副作用是一个反模式,但可以移动到componentWillMount。
我发现原因是:
const mapStateToProps = (state) => {
return {
notifications: state.get("notifications").get("notifications").toJS()
}
}
如果我不返回通知,那么它就可以工作。但是为什么呢?
import {connect} from "react-redux"
import {removeNotification, deactivateNotification} from "./actions"
import Notifications from "./Notifications.jsx"
const mapStateToProps = (state) => {
return {
notifications: state.get("notifications").get("notifications").toJS()
}
}
const mapDispatchToProps = (dispatch) => {
return {
closeNotification: (notification) => {
dispatch(deactivateNotification(notification.id))
setTimeout(() => dispatch(removeNotification(notification.id)), 2000)
}
}
}
const NotificationsBotBot = connect(mapStateToProps, mapDispatchToProps)(Notifications)
export default NotificationsBotBot
import React from "react"
class Notifications extends React.Component {
render() {
return (
<div></div>
)
}
}
export default Notifications
更新
在进一步调试后,我发现上述可能并不是根本原因,我可以让通知保持,但需要删除dispatch(push("/domains"))
我的重定向。
这是我的登录方式:
export function doLogin (username, password) {
return function (dispatch) {
dispatch(loginRequest())
console.log("Simulated login with", username, password)
setTimeout(() => {
dispatch(loginSuccess(`PLACEHOLDER_TOKEN${Date.now()}`))
dispatch(addNotification({
children: "Successfully logged in",
type: "accept",
timeout: 2000,
action: "Ok"
}))
dispatch(push("/domains"))
}, 1000)
}
}
我发现派遣引起了警告,但为什么?我的域页面目前没有太多内容:
import {connect} from "react-redux"
import DomainsIndex from "./DomainsIndex.jsx"
export default connect()(DomainsIndex)
域名索引
export default class DomainsIndex extends React.Component {
render() {
return (
<div>
<h1>Domains</h1>
</div>
)
}
}
更新2
这是我的 App.jsx
文件。 <Notifications />
是用于显示通知的部分。
<Provider store={store}>
<ConnectedRouter history={history}>
<Layout>
<Panel>
<Switch>
<Route path="/auth" />
<Route component={TopBar} />
</Switch>
<Switch>
<Route exact path="/" component={Index} />
<Route path="/auth/login" component={LoginBotBot} />
<AuthenticatedRoute exact path="/domains" component={DomainsPage} />
<AuthenticatedRoute exact path="/domain/:id" component={DomainPage} />
<Route component={Http404} />
</Switch>
<Notifications />
</Panel>
</Layout>
</ConnectedRouter>
</Provider>
componentWillMount
或render
中触发操作时,您会看到此错误。甚至可能是由于错误,例如在编写onClick={action()}
而不是onClick={action}
时发生的。 - SulthandoLogin
,看看是哪个方法出了问题,可能是addNotification
还是push
方法,目前没有足够的信息来完全理解发生了什么。 - cabolanoz