gpt4 book ai didi

javascript - React Redux - 存储更新、组件重新渲染……但不使用新数据

转载 作者:行者123 更新时间:2023-11-30 15:19:37 25 4
gpt4 key购买 nike

我有一个复杂的应用程序有一个问题,我已将其减少到以下 3 个文件。本质上,发生的事情是:

  • 组件加载并呈现初始文本
  • 随后会触发欺骗 API,它会调用 this.props.route.onLoadData()
  • 这反过来调用一个 reducer,它返回一个包含更新文本的新对象
  • 组件相应地重新呈现,但不使用更新后的文本

我正在使用 <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)

问题.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

}
}

最佳答案

根据这两段代码:

var routes = [
...
data: initialState,
...
]

render() {
var text = this.props.route.data.text
...
}

看起来您所做的总是引用同一条数据(即 initialState),甚至没有触及存储。

更新。您需要做的是通过react-redux 将您的组件 连接到存储,并在您的 中使用存储值>组件

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);

关于javascript - React Redux - 存储更新、组件重新渲染……但不使用新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43933878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com