我应该如何使用 React/redux 在渲染方法中传递数据
How should I pass data in my render method with React/redux
我正在尝试使以下反应条形图适应我的 react/redux 项目:http://codepen.io/clindsey/collab/RRZBQm/。大多数代码对我来说都可以,但是我不太了解渲染部分:
setTimeout(() => {
const data = {'alpha': 82, 'bravo': 20, 'charlie': 68};
const size = [480, 320];
const margins = [40, 40, 40, 40];
ReactDOM.render(
<BarChart {...{data, margins, size}} />
, document.getElementById('js-app'));
}, 0);
为什么在此示例中,"const" 通过 BarChart 元素传入 ReactDOM.render 函数?
在将其适应我的本地项目时,我的容器中有以下代码:
const App = () => (
<div>
<Component1 />
<Component2 />
<BarChart />
</div>
);
export default App;
然后我使用 mapStateToProps
函数传递 const data
、const size
和 const margins
,像这样:
const data = {'alpha': 82, 'bravo': 20, 'charlie': 68};
const size = [480, 320];
const margins = [40, 40, 40, 40];
function mapStateToProps(state) {
return {
data: data,
size: size,
margins: margins,
};
};
它工作正常,但我不太明白我在做什么。不确定这是好习惯还是天堂有意义。
谢谢。
mapStateToProps 的整个想法是 link 你的 Redux 存储到你的(在你的情况下)React 组件。通常你会像这样使用它
function mapStateToProps(state){
return {
propertyOne: state.myPropertyOne, //state.myPropertyOne comes from your redux store, when you return this object, your component gets this object
propertyTwo: state.myPropertyTwo
};
}
您不必将 const
变量传递到函数中即可运行。如果它们在该文件中,您可以直接使用它们。
我正在尝试使以下反应条形图适应我的 react/redux 项目:http://codepen.io/clindsey/collab/RRZBQm/。大多数代码对我来说都可以,但是我不太了解渲染部分:
setTimeout(() => {
const data = {'alpha': 82, 'bravo': 20, 'charlie': 68};
const size = [480, 320];
const margins = [40, 40, 40, 40];
ReactDOM.render(
<BarChart {...{data, margins, size}} />
, document.getElementById('js-app'));
}, 0);
为什么在此示例中,"const" 通过 BarChart 元素传入 ReactDOM.render 函数?
在将其适应我的本地项目时,我的容器中有以下代码:
const App = () => (
<div>
<Component1 />
<Component2 />
<BarChart />
</div>
);
export default App;
然后我使用 mapStateToProps
函数传递 const data
、const size
和 const margins
,像这样:
const data = {'alpha': 82, 'bravo': 20, 'charlie': 68};
const size = [480, 320];
const margins = [40, 40, 40, 40];
function mapStateToProps(state) {
return {
data: data,
size: size,
margins: margins,
};
};
它工作正常,但我不太明白我在做什么。不确定这是好习惯还是天堂有意义。
谢谢。
mapStateToProps 的整个想法是 link 你的 Redux 存储到你的(在你的情况下)React 组件。通常你会像这样使用它
function mapStateToProps(state){
return {
propertyOne: state.myPropertyOne, //state.myPropertyOne comes from your redux store, when you return this object, your component gets this object
propertyTwo: state.myPropertyTwo
};
}
您不必将 const
变量传递到函数中即可运行。如果它们在该文件中,您可以直接使用它们。