我最近开始学习React / Redux,现在我正在尝试构建一个小的单页应用程序。
最近,我遇到了一个我不了解且无法解决的问题。
让我向您展示代码:
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
import App from './components/App'
import Home from './components/Home'
import About from './components/About'
const reducer = (state = {}, action) => {
return state
}
const store = createStore(
combineReducers({
reducer,
routing: routerReducer
})
)
const history = syncHistoryWithStore(hashHistory, store)
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<Route path='/' component={App}>
<IndexRoute component={Home}/>
<Route path='about' component={About}/>
</Route>
</Router>
</Provider>
), document.getElementById('root'))
基本上,这是来自react-router-redux GitHub页面(向下滚动至Tutorial一节)的示例-唯一的区别是,我正在使用hashHistory。
import React, { Component, PropTypes } from 'react'
import Navigation from './Navigation'
export default class App extends Component {
render() {
return (
<div>
<Navigation/>
{this.props.children}
</div>
)
}
}
App.propTypes = {
children: PropTypes.node
}
import React, { Component } from 'react'
import { Link, IndexLink } from 'react-router'
export default class Navigation extends Component {
render() {
return (
<ul role='nav'>
<li><IndexLink to='/' activeStyle={{ color: 'red' }}>Home</IndexLink></li>
<li><Link to='/about' activeStyle={{ color: 'red' }}>About</Link></li>
</ul>
)
}
}
Home和About组件只是呈现一个<h1>标题以可视化SPA的状态。
到目前为止,一切都按您期望的那样正常!当用户单击“关于”链接时,URL会相应更改,并且链接会变为红色(由于activeStyle属性)。
但是这是我的问题(感谢您继续阅读此内容):
我想通过react-redux connect()包装<Navigation>组件。这是我的新版本
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Link, IndexLink } from 'react-router'
class Navigation extends Component {
render() {
return (
<ul role='nav'>
<li><IndexLink to='/' activeStyle={{ color: 'red' }}>Home</IndexLink></li>
<li><Link to='/about' activeStyle={{ color: 'red' }}>About</Link></li>
</ul>
)
}
}
const NavigationContainer = connect()(Navigation)
export default NavigationContainer
但是现在activeStyle功能似乎已损坏...当我浏览我的应用程序时,当前活动的链接不再更改其颜色。
我真的试图解决这个问题几个小时了:(非常感谢您的帮助!
react-redux的connect()阻止Navigation和随后的链接在位置状态更改时重新呈现。
如果添加console.log("Navigation render")
Navigation的render,则会看到在添加connect()函数之后,组件不会在位置状态更改时重新呈现。
有避免的方法
1.way:为了在位置更改时重新渲染Navigation comp,您可以添加prop,类似这样location={this.props.location}
export default class App extends Component {
render() {
return (
<div>
<Navigation location={this.props.location}/>
{this.props.children}
</div>
)
}
}
2.way:添加{pure:false}
到connect()。文档链接
export default connect(mapStateToProps, actions, null, { pure: false })(Navigation);
3.way:此问题已在React Router 3.0.0-alpha.1及更高版本中修复。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句