使用onClick进行反应以将其发送到操作

时间:2017-03-20 23:43:01

标签: javascript reactjs asynchronous

我正在尝试使用onClick将两个不同的状态信息发送到操作事件。

user.user.user_id和post.book_id来自应用程序状态,我想将该信息传递给操作。

 <div 
      onClick={() => { this.props.addToMyPage({
                      user_id: user.user.user_id, book_id: post.book_id}) }}>
                Add this to my page
</div>

部分

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { selectBook } from '../actions/index';
import { addToMyPage } from '../actions/index';
import { Link } from 'react-router';
class BookDetails extends Component {
     componentWillMount() {
        this.props.selectBook(this.props.params.id);
    }
    render() {
        const {post} = this.props;
        const {user} = this.props;
        console.log("This Book", post)
        if(!post) {
           return <div>Loading...</div>
        }
        return (
            <div>

                <h1>Title: {post.title}</h1>
                <h2>Pages: {post.pages}</h2>
                <div>Reviews:</div>
                <div 
                    onClick={() => { this.props.addToMyPage(user.user, post) }}>
                    Add this to my page
                </div>

            </div>
        )

    }
}
function mapStateToProps(state) {
    return {
        post: state.books.post,
        user: state.user.post

    }
}
export default connect(mapStateToProps, {selectBook, addToMyPage})(BookDetails);

当我这样做时,它只传递user.user信息,并在谷歌控制台中显示

  

动作必须是普通对象。使用自定义中间件进行异步操作。

不完全确定这意味着什么。 我在index.js文件中设置了中间件。

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import reducers from './reducers';
import routes from './routes';
import promise from 'redux-promise';

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <Router history={browserHistory} routes={routes} />
  </Provider>
  , document.querySelector('.container'));

//动作

export function addToMyPage(user, post) {
    console.log("mypage" , user, post);
    const request = axios.post(`${ROOT_URL}api/mypage`, user, post);

    return {
        type: ADD_MYPAGE,
        payload: request
    }
}

1 个答案:

答案 0 :(得分:0)

Rob M回答需要在您的操作文件中返回对象。我注释掉了抛出错误的返回对象。

  function addToMyPage(user, post) { return { type: 'ADD_TO_MY_PAGE', user, post }; }