【发布时间】:2017-09-04 08:05:24
【问题描述】:
我收到了错误
警告:setState(...):在现有状态转换期间无法更新(例如在
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>
【问题讨论】:
-
你能把代码上传到一个仓库让我们玩吗?这个设置有点难以理解。
-
附带说明,您应该使用 .getIn([]),而不是使用 .get().get()。
-
根据我的经验,这与动作的结构无关,而与触发动作的位置有关。通常,您在从
componentWillMount或render触发操作时会看到此错误。即使是错误的,例如当写onClick={action()}而不是onClick={action}时。 -
你能不能在action creator
doLogin中逐行查看哪个在抱怨,是addNotification还是push方法,现在没有那个充分了解正在发生的事情的大量信息。 -
@cabolanoz 它的推动力。没有它,我不会收到警告。
标签: javascript reactjs redux react-redux