我希望浏览器显示EditMessage
组件 (in Dashboard.js
) 如果showEdit
为真(见initState
in MessageReducer.js
)和CreateMessage
组件 ifshowEdit
为假但我的代码不起作用。我的应用程序没有注意到Dashboard.js
.
我尝试在其中包含this.setState
方法,Dashboard.js
但出现错误:“超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况”。我还尝试将 的值showTypeForm
直接分配给 props 并输出(请参阅 中的注释Dashboard.js
),但这种方法也不起作用。我不确定要使用哪种生命周期方法。
我的代码看起来像这样。MessageSummary.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
class MessageSummary extends Component {
editClick = (e) => {
e.preventDefault();
this.props.editMessage('123', 'I love web development'); //test values
}
render() {
return (
<button className="edit-message" onClick={this.editClick}>Edit
Message</button> // this button changes showEdit in MessageReducer.js
)
}
}
const mapDispatchToProps = (dispatch) => {
return {
editMessage: (id, newMessage) => dispatch(editMessage(id, newMessage))
}
}
export default connect(null, mapDispatchToProps)(MessageSummary);
MessageActions.js:
export const editMessage = (id, newMessage) => {
return (dispatch, getState, { getFirebase, getFirestore }) => {
dispatch({
type: "EDIT_MESSAGE"
});
}
}
RootReducer.js:
// importing everything
const rootReducer = combineReducers({
message: messageReducer
});
export default rootReducer;
MessageReducer.js:
const initState = {
showEdit: false
};
const messageReducer = (state = initState, action) => {
switch (action.type) {
case 'EDIT_MESSAGE':
initState.showEdit = !initState.showEdit; // toggling showEdit
return state;
default:
return state;
}
}
export default messageReducer;
仪表板.js:
// importing everything
class Dashboard extends Component {
state = {
showEdit: this.props.message.showEdit
}
render() {
const { message } = this.props; // destructuring
// this.setState({
// showEdit: message.showEdit
// })
// const showTypeForm = message.showEdit ? <EditMessage /> : <CreateMessage />;
return (
<div className="message-form">
{this.state.showEdit ? <EditMessage /> : <CreateMessage />}
// {showTypeForm }
</div>
)
}
const mapStateToProps = (state) => {
return {
message: state.message
}
}
}
export default connect(mapStateToProps)(Dashboard);