取react-redux的值
时间: 2023-08-29 16:13:50 浏览: 32
要获取 React-Redux 中的值,你需要先连接组件到 Redux store,然后使用 mapStateToProps 函数从 store 中获取值并将其映射到组件的 props 上。
以下是一个示例:
```javascript
import React from 'react';
import { connect } from 'react-redux';
class MyComponent extends React.Component {
render() {
return (
<div>
<p>My value from Redux: {this.props.myValue}</p>
</div>
);
}
}
const mapStateToProps = state => ({
myValue: state.myValue
});
export default connect(
mapStateToProps
)(MyComponent);
```
在上面的示例中,我们首先导入 React 和 connect 函数。然后,我们创建了一个组件 MyComponent,并在 render 方法中使用 this.props.myValue 显示从 Redux store 中获取的值。
接下来,我们定义了一个名为 mapStateToProps 的函数,它将 Redux store 中的值映射到组件的 props 上。在这个示例中,我们只需要从 Redux store 中获取一个名为 myValue 的值并将其映射到组件的 props 上。
最后,我们使用 connect 函数将组件连接到 Redux store,并将 mapStateToProps 函数传递给它。这将确保我们可以访问 Redux store 中的值并将其传递到组件中。