我目前正在创建一个评论/留言板风格的网络应用,并且无法按照我想要的方式呈现评论。我希望评论列表在完成后立即更新,但我的组件没有收到newProps。我在某个地方改变我的状态而根本没有看到它吗?谢谢!
我的容器组件:
class Ritmo extends Component {
componentDidMount = () => {
this.props.getComments()
}
renderComments = () => {
return this.props.comments.comments.map(e => {
return (
<Comment
key={e.id}
username={e.username}
comment={e.comment}
/>
)
})
}
render() {
return (
<div className={container}>
<div className={projectContainer}>
<Text>This is my project, RITMO</Text>
<Image imageSource="../../assets/instructor-screen.png" />
</div>
<div className={formContainer}>
<Form />
{this.renderComments()}
</div>
</div>
)
}
}
const mapStateToProps = ({ comments }) => {
return { comments }
}
export default connect(mapStateToProps, { getComments })(Ritmo)
我的行动:
export const GET_COMMENTS = 'get_comments'
export const getComments = () => {
const request = axios.get('http://localhost:5000/comments')
return {
type: GET_COMMENTS,
payload: request
}
}
export const POST_COMMENT = 'post_comment'
export const postComment = (values) => {
const request = axios.post('http://localhost:5000/comments', values)
return {
type: POST_COMMENT,
payload: request
}
}
我的减速机:
import { GET_COMMENTS, POST_COMMENT } from '../actions'
const initialState = {
comments: []
}
export default (state = initialState, action) => {
switch(action.type) {
case GET_COMMENTS:
return {
...state,
comments: action.payload
}
case POST_COMMENT:
return {
...state
}
default:
return state
}
}
答案 0 :(得分:0)
1。
您的行为getComments
和postComment
必须为thunks,因为它们会异步。
这是一段有助于解释thunks服务角色的视频:
https://egghead.io/lessons/javascript-redux-dispatching-actions-asynchronously-with-thunks
(当你applyMiddleware
时,你需要使用Redux&#39; createStore
来连接thunk。)
这些thunks不会被你的减速器直接解释,而是......
2。
在getComments
和/或postComment
之后,您需要创建常规操作来处理您想要执行的操作。
您希望将获取的评论存储在状态中,以便您执行SET_COMMENTS
操作,并且您的reducer将按照您GET_COMMENTS
的方式处理它有线。
您的postComment
thunk不需要定期操作(使用您当前的代码),因为您在发布后没有更改Redux状态以响应任何内容。
这些步骤一起如下:
// Actions
const SET_COMMENTS = "set_comments";
const setComments = comments => ({
type: SET_COMMENTS,
payload: comments
});
// Thunks
const getCommentsAsync = () => dispatch => {
return axios
.get("http://localhost:5000/comments")
.then(comments => dispatch(setComments(comments)));
};
const postCommentAsync = comment => dispatch => {
return axios.post("http://localhost:5000/comments", comment);
};
// Reducer
const initialState = {
comments: []
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case SET_COMMENTS:
const comments = action.payload;
return {
...state,
comments
};
default:
return state;
}
};