我有一个复杂的应用程序有一个问题,我已经减少到下面的3个文件。基本上,正在发生的事情是:
this.props.route.onLoadData()
我正在使用<Provider/>
和connect()
- 都没有成功。
有什么想法吗?
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, hashHistory } from 'react-router'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import Reducers from './reducers'
import Problem from './Problem'
var store = createStore(Reducers)
var routes = [
{ path: '/problem',
component: Problem,
data: store.getState(),
onLoadData: (res) => store.dispatch({ type: 'LOAD_DATA', data: res })
}
]
var render = function() {
return ReactDOM.render(
<Provider store={store}>
<Router history={hashHistory} routes={routes}/>
</Provider>,
document.getElementById('app')
)
}
render()
store.subscribe(render)
problem.js
import React from 'react'
import { connect } from 'react-redux'
var ProblemContainer = React.createClass({
spoofAPI() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ text: 'updated text' })
}, 1000)
})
},
componentDidMount() {
this.spoofAPI().then((res) => {
return this.props.route.onLoadData( res )
}, console.error)
},
render() {
var text = this.props.route.data.text
console.log('render:', text)
return (
<div>{text}</div>
)
}
})
const mapState = state => ({ text: state })
export default connect(mapState)(ProblemContainer)
reducers.js
export default (state = { text: 'initial text' }, action) => {
switch (action.type) {
case 'LOAD_DATA':
var newState = Object.assign({}, state)
console.log('reducer - existing state: ', newState.text)
newState.text = action.data.text
console.log('reducer - receives: ', action.data.text)
var returnObject = Object.assign({}, state, newState)
console.log('reducer - returnObject: ', returnObject)
return returnObject
default:
return state
}
}
答案 0 :(得分:2)
根据这两段代码:
var routes = [
...
data: initialState,
...
]
和
render() {
var text = this.props.route.data.text
...
}
看起来你正在做的事情总是引用同一条数据(initialState
),甚至没有触摸商店。
更新。您需要做的是通过Component
将react-redux
与商店相关联,并使用Component
中的商店值。
import React from 'react'
import { connect } from 'react-redux'
const Foo = React.createClass({
...
render() {
var text = this.props.text
console.log('render:', text)
return (
<div>{text}</div>
)
}
})
const mapState = state => ({ text: state });
export default connect(mapState)(Foo);