我有这个动作
export const UserIsLoggedIn = isLoggedIn => (
{ type: types.USER_IS_LOGGED_IN, isLoggedIn });此actionConstant
export const USER_IS_LOGGED_IN = "USER_IS_LOGGED_IN";像这样的index.js
import { UserIsLoggedIn } from "./redux/actions";
getUser = () => {
this.authService.getUser().then(user => {
if (user) {
this.props.UserIsLoggedIn(true);
}
}
}
const mapDispatchToProps = {
UserIsLoggedIn
}
export default connect(mapStateToProps, mapDispatchToProps) (Index);所以最终通过上面的代码我得到this.props.UserIsLoggedIn不是一个函数错误,如果我做UserIsLoggedIn(true);什么都不会发生…我不太明白问题出在哪里。
在redux chrome扩展中,我可以使用以下命令进行调度,而不会出现错误:
{
type: "USER_IS_LOGGED_IN", isLoggedIn : true
}下面是索引的一般外观
const store = configureStore();
class Index extends Component {
componentWillMount() {
this.getUser();
}
getUser = () => {
this.authService.getUser().then(user => {
if (user) {
console.log(this.props.isUserLoggedIn);
toastr.success("Welcome " + user.profile.given_name);
} else {
this.authService.login();
}
});
};
render() {
return (
<Provider store={store}>
<BrowserRouter>
<Route path="/" exact component={App} />
<Route path="/:type" component={App} />
</BrowserRouter>
</Provider>
);
}
}
function mapStateToProps(state) {
return {
isUserLoggedIn : state.User.isLoggedIn
}
}
const mapDispatchToProps = {
UserIsLoggedIn
}
export default connect(mapStateToProps, mapDispatchToProps) (Index);
ReactDOM.render(<Index />, document.getElementById("root"));
serviceWorker.unregister();注意:另一方面,mapStateToProps也不能工作...
发布于 2019-05-13 21:27:46
感谢@Yusufali2205和@RyanCogswell的帮助,但这些并没有解决问题。
对于正在寻找答案的人来说: index.js是我的React中要加载的第一个文件,然后是App.js。通过这种设置,我在index.js中使用了<Provider store={store}>,而在index.js中,我不能访问render方法中的存储,也不能访问任何生命周期,如willmount、甚至didmount或willunmount。要访问商店,请在index.js中使用<Provider store={store}>创建它,并在App.js中访问商店项目。
关于调度操作错误,如果我尝试使用此代码{this.props.UserIsLoggedIn(true)}在render方法中调度,我仍然会收到Objects are not valid as a React child (found: object with keys {type, isLoggedIn}). If you meant to render a collection of children, use an array instead.错误。我尝试这样做只是为了看看调度是否起作用,我不打算让它实际上在渲染中。当我用console.log包装它时,它工作得很好,就像这样的{console.log(this.props.UserIsLoggedIn(true))}。
当我将这些分派器转移到生命周期方法下时,它们在没有console.log包装器的情况下工作得很好……像这样
componentWillMount() {
console.log(this.props.isUserLoggedIn)
this.props.UserIsLoggedIn(true)
}发布于 2019-05-11 05:08:54
无论在哪里使用这个导出的组件,都需要对<Provider store={store}>进行包装。它不能在Index的render方法内。按照现在的方式,connect方法将无法访问您的store。
你需要这样的东西:
ReactDOM.render(<Provider store={store}><Index /></Provider>, document.getElementById("root"));然后从Index中的render方法中删除Provider部分
render() {
return (
<BrowserRouter>
<Route path="/" exact component={App} />
<Route path="/:type" component={App} />
</BrowserRouter>
);
}发布于 2019-05-11 04:44:09
你需要调度你的行动
const mapDispatchToProps = dispatch => ({
UserIsLoggedIn: (value) => {
dispatch(UserIsLoggedIn(value));
}
});更新:如果你想使用对象语法,你需要将该动作包装在一个函数中:
const mapDispatchToProps = {
UserIsLoggedIn: (value) => UserIsLoggedIn(value),
};https://stackoverflow.com/questions/56084437
复制相似问题