gpt4 book ai didi

javascript - 无法从 Redux 获取值到 props

转载 作者:行者123 更新时间:2023-12-03 01:33:28 25 4
gpt4 key购买 nike

我无法从 Redux 获取 props 值,我检查了 reducer 、存储、action JS 文件,一切正常。即使我也可以在下面的 mapsStateToProps 函数内的 console.log("MAPSSTOSTATEPROPS", state) 中看到正确打印的状态。

但是当我提供 this.props.posts 来访问这些值时,我没有得到它们。不确定,我在这里做错了什么。有人可以帮助我吗?

posts.js:

class Posts extends Component {
componentWillMount() {
this.props.fetchPosts();
**console.log(this.props.posts); // gives empty array result**
}

render() {
return (
<div>
<h2>Posts</h2>
</div>
)
}

componentDidMount() {
console.log("DID mount", this.props);
}
}

Posts.propTypes = {
fetchPosts: PropTypes.func.isRequired,
posts: PropTypes.array
}

const mapsStateToprops = (state) => {
**console.log("MAPSTOSTATEPROPS", state)** // gives correct result from current state
return {
posts: state.items
}
};

export default connect(mapsStateToprops, {fetchPosts}) (Posts);

最佳答案

class Posts extends Component {

/* use did mount method because all will-methods
are will be deprecated in nearest future */
componentDidMount() {

/* on component mount you initiate async loading data to redux store */
this.props.fetchPosts();
/* right after async method you cannot expect to retrieve your data immediately so this.props.posts will return [] */
console.log(this.props.posts);
}

render() {
/* here you getting posts from props*/
const { posts } = this.props;

return (
<div>
<h2>Posts</h2>
/* here you render posts. After async method will be completed
and dispatch action with retrieved data that will cause rerender
of component with new props */
{posts.map(post => (<div>post.name</div>))}
</div>
)
}
}

Posts.propTypes = {
fetchPosts : PropTypes.func.isRequired,
posts : PropTypes.array
}

const mapsStateToprops = (state) => {
/* first call will log an empty array of items,
but on second render after loading items to store they will
appear in component props */
console.log("MAPSTOSTATEPROPS", state)
return {
posts : state.items || [];
}

关于javascript - 无法从 Redux 获取值到 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51189764/

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