我有以下设置:
Dashboard.jsx:
import React, { Component } from "react";
import { addFlashMessage } from "../actions/flashMessages";
import RoomsList from "./RoomsList";
import PropTypes from "prop-types";
import FlashMessagesList from "../components/flash/FlashMessagesList";
import { connect } from "react-redux";
class Dashboard extends Component {
render() {
return (
<div className="componentContent">
<FlashMessagesList />
<RoomsList addFlashMessage={addFlashMessage} />
</div>
);
}
}
Dashboard.propTypes = {
addFlashMessage: PropTypes.func.isRequired
};
export default connect(null, { addFlashMessage })(Dashboard);
RoomsList:
import React, { Component } from "react";
import PropTypes from "prop-types";
class RoomsList extends Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
}
onClick() {
this.props.addFlashMessage({
type: "success",
text: "You signed up successfully. Welcome."
});
}
render() {
return (
<div className="componentContent" onClick={this.onClick} />
);
}
}
RoomsList.propTypes = { addFlashMessage: PropTypes.func.isRequired };
export default RoomsList;
Actions.js:
export function addFlashMessage(message) {
console.log("action called");
return {
type: ADD_FLASH_MESSAGE,
message
};
}
Reducers.js
import { ADD_FLASH_MESSAGE } from "../actions/types";
import shortid from "shortid";
export default (state = [], action = {}) => {
console.log(action);
switch (action.type) {
case ADD_FLASH_MESSAGE:
return [
...state,
{
id: shortid.generate(),
type: action.message.type,
text: action.message.text
}
];
default:
return state;
}
};
index.js:
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import { BrowserRouter as Router, Route } from "react-router-dom";
// Redux
import { Provider } from "react-redux";
import thunk from "redux-thunk";
import { createStore, applyMiddleware, compose } from "redux";
import rootReducer from "./rootReducer";
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
)
);
ReactDOM.render(
<Provider store={store}>
<Router>
<div className="navSwitch">
<Route path="/" component={App} />
</div>
</Router>
</Provider>,
document.getElementById("root")
);
actions.js
console.log显示确定,但在reducer.js
中,console.log没有被执行,因此只返回默认状态。
有人可以找出问题所在吗?
答案 0 :(得分:4)
在Dashboard
组件中,您通过addFlashMessage
将props
操作传递给组件,但在组件内部您使用导入功能而不是通过一个。它们看起来相同(因为它们实际上是同一函数的不同版本),但由于导入函数未包含在dispatch()
中 - 调用它不会触发Redux操作。 / p>
修复很明显 - 您需要在this.props.addFlashMessage
使用<RoomsList addFlashMessage={addFlashMessage} />
:{{1}}