reactjs - 将 Redux 状态传递给子组件时遇到问题
问题描述
我是 Redux 的新手,我一直在使用 Redux 文档中第一个示例项目的代码。该示例不使用容器或具有单独的操作文件,所以我想我会从那里开始并尝试将它抽象一点。
该项目没有App
组件,并且index.js文件看起来像这样开始:
import React from 'react'
import ReactDOM from 'react-dom'
import { createStore } from 'redux'
import Counter from './components/Counter'
import counter from './reducers'
const store = createStore(counter)
const rootEl = document.getElementById('root')
const render = () => ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({ type: 'INCREMENT' })}
onDecrement={() => store.dispatch({ type: 'DECREMENT' })}
/>,
rootEl
)
render()
store.subscribe(render)
我首先更改了它,以便它安装了一个App
组件:
...
import { Provider } from 'react-redux':
...
const render = () => ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
我已将Counter
组件移动到App.js中,并尝试使用它mapStateToProps
来引入初始状态(state = 0
在减速器中设置为):
import React from 'react';
import Counter from '../components/Counter.js';
import { connect } from 'react-redux';
class App extends React.Component {
render() {
return(
<div>
<Counter value={value} />
</div>
);
}
}
const mapStateToProps = (state) => {
return { value: state.value };
}
export default connect(mapStateToProps)(App);
我正在尝试传递设置Counter
在.value
mapStateToProps
使用上面的代码,我在以下位置收到错误<Counter value={value} />
:
'value' 未定义 no-undef
听起来很疯狂,我想也许我必须在函数内部初始化才能value
使这项工作:constructor
App
constructor() {
super(props);
this.state = {
value: 0
}
}
这没有用,而且无论如何都没有意义,因为状态是在减速器中初始化的。
解决方案
它非常简单,您做对了,但您只需要在渲染方法中进行一些更改,以获得更新的值,您的问题将得到解决。
只需在您的 App 组件中进行这些更改即可。
import React, {Component} from 'react';
import Counter from '../components/Counter.js';
import { connect } from 'react-redux';
class App extends Component {
render() {
const {
props: {
value
}
} = this;
return(
<div>
<Counter value={value} />
</div>
);
}
}
你不需要initialize
在constructor
方法中赋值。
推荐阅读
- javascript - Bootstrap-vue - 动态设置表变体
- python - 如何在表单数据中发送带有 $ 的 python 发布请求
- spring-boot - 如何正确使用弹簧数据的二级索引
- elasticsearch - 如何在弹性搜索的索引中创建计算字段?
- javascript - 正则表达式:如何(更好地)优化来自/用于消息的文本
- google-apps-script - 如果 Google 工作表宏中的特定工作表为空,则隐藏或过滤行或列
- java - 为什么 Java WatchService 保持打开的文件句柄?
- excel - 计算一条信息出现的频率并计算该平均值
- c# - 将 2 个字符列表与二进制数字进行比较,目的是将第一个列表中的每个 0 替换为 1,如果在另一个列表中具有相同的位置 1
- ios - 应用程序在后台时,Firestore 存储上传任务观察器未执行