【发布时间】:2019-11-06 06:19:25
【问题描述】:
我必须显示用户列表,单击按钮时我想在按钮内显示文本。 UserHeader 是我从我的记录列表 (PostList) 中导入的组件。我意识到,一旦我单击按钮,所有列表元素的操作都会受到影响,我认为这是因为减速器的状态数组被记录填充,并且每次显示 UserHeader 时,它都会显示按钮内的文本。我只想在我已经处理的列表元素上显示文本,而不是整个列表。请帮助我如何使用 redux 做到这一点。我指的是UserHeader上按钮的selectPost()函数onClick
// reducers.js
export const Reducer_posts = (state=[], action) => {
switch (action.type){
case 'FETCH_POSTS':
return action.payload
default:
return state;
}
};
export const Reducer_users = (state=[], action) => {
switch (action.type){
case 'FETCH_USER':
return [...state, action.payload];
default:
return state;
}
};
export const Reducer_select = (state=[], action) => {
switch (action.type){
case 'SELECT_POST':
return action.payload;
case 'DELETE_SELECT':
return null;
default:
return state;
}
};
//UserHeader.js
import React from 'react';
import { connect } from 'react-redux';
import { fetchUser, selectPost, deleteSelect } from '../actions';
class UserHeader extends React.Component {
componentDidMount () {
this.props.fetchUser(this.props.userId);
}
render() {
console.log(this.props.select)
if(!this.props.user) {
return <div> Loading... </div>
}
return <button onClick={this.props.selectPost} className="header"> {this.props.select} </button>
}
}
const mapStateToProps = (state, ownProps) => {
return {
user: state.users.find(user => user.id === ownProps.userId),
select: state.select
};
}
export default connect(mapStateToProps, { fetchUser, selectPost, deleteSelect })(UserHeader);
//PostList.js
import React from 'react';
import { connect } from 'react-redux';
import { fetchPosts, selectPost } from '../actions';
import UserHeader from './UserHeader'
class PostList extends React.Component {
componentDidMount(){
this.props.fetchPosts();
}
renderList() {
return this.props.posts.map(post => {
return (
<div className = "item" key={post.id}>
<i className="large middle aligned icon user" />
<div className="content">
<div className = "description">
<h2> {post.title} </h2>
<p> {post.body} </p>
</div>
<UserHeader userId = {post.userId}/>
</div>
</div>
)
})
}
render(){
return <div className = "ui relaxed divided list"> {this.renderList()} </div>;
};
}
const mapStateToProps = state => {
return { posts: state.posts, select: state.select };
};
export default connect( mapStateToProps, { fetchPosts, selectPost })(PostList);
【问题讨论】:
标签: reactjs redux react-redux redux-form redux-thunk