使用Redux从表单发布数据

时间:2019-12-19 10:26:46

标签: javascript reactjs redux

另一个新手问题。我想用我的表格发表帖子。我有看起来像这样的Post.js:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

import PostForm from './PostFormContainer';

export class Post extends Component {
  static propTypes = {
    posts: PropTypes.any,
    fetchPosts: PropTypes.func,
    sendPostData: PropTypes.func,
  };

  componentDidMount() {
    const { fetchPosts } = this.props;
    fetchPosts();
  }

  // onSubmit = (e, id, title, body) => {
  //   e.preventDefault();
  //   axios
  //     .post('https://jsonplaceholder.typicode.com/posts', {
  //       id,
  //       title,
  //       body,
  //     })
  //     .then(res =>
  //       this.setState({
  //         posts: [...this.state.posts, res.data],
  //       })
  //     );
  // };

  // onSubmit(e, id, title, body) {
  //   e.preventDefault();
  //   console.log('data');
  //   console.log('data', id);
  //   console.log('data', title);
  //   console.log('data', body);

  //   this.props.sendPostData(id, title, body);
  //   console.log('sendPostData', this.props.sendPostData(id, title, body));
  // }

  render() {
    console.log('props', this.props);
    const { posts } = this.props;
    if (!posts.length) {
      return (
        <div>
          <PostForm addPost={this.onSubmit} />
        </div>
      );
    } else {
      return (
        <div>
          <PostForm addPost={this.onSubmit} />
          <br />

          <div>
            {posts.map(post => (
              <div key={post.id}>
                <h3>{post.title}</h3>
                <p>{post.body}</p>
              </div>
            ))}
            ;
          </div>
        </div>
      );
    }
  }
}

export default Post;

我在哪里<PostForm addPost={this.onSubmit} /> 我的PostForm.js看起来像这样:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class PostForm extends Component {
  ///state = {
   // title: '',
   // body: '',
  //};

  static propTypes = {
    posts: PropTypes.any,
    // fetchPosts: PropTypes.func,
    sendPostData: PropTypes.func,
  };

  //onChange = e => {
    //this.setState({
      // e.target.name zawsze będzie targetował pole z value i zmieniał jego stan
     // [e.target.name]: e.target.value,
   // });
  //};

  // onSubmit(e, id, title, body) {
  //   e.preventDefault();

  //   console.log('data');
  //   console.log('data', id);
  //   console.log('data', title);
  //   console.log('data', body);
  // }

  onSubmit(e, id, title, body) {
    e.preventDefault();
    console.log('data');
    console.log('data', id);
    console.log('data', title);
    console.log('data', body);
    // const post = {
    //   title,
    //   body,
    // };

    this.props.sendPostData(title, body);
    // console.log('sendPostData', this.props.sendPostData(post));
  }

  render() {
    console.log('props form', this.props);
    const { title, body } = this.props;
    return (
      <div>
        <h1> Add Post </h1>
        <form onSubmit={e => this.onSubmit(e, title, body)}>
          <div>
            <label>Title: </label>
            <input
              type='text'
              name='title'
              value={title}
              onChange={this.onChange}
            />
          </div>
          <div>
            <label>Body: </label>
            <textarea name='body' value={body} onChange={this.onChange} />
          </div>
          <button type='submit'>Submit</button>
        </form>
      </div>
    );
  }
}

export default PostForm;

在这里,我想将其发送给我。 我有两个容器文件 PostFormContainer.js

import { connect } from 'react-redux';
import PostForm from './PostForm';
import { sendPost } from '../reducers/postReducers';

const mapStateToProps = state => ({
  posts: state.posts,
});

const mapDispatchToProps = dispatch => ({
  sendPostData: post => dispatch(sendPost(post)),
});

export default connect(mapStateToProps, mapDispatchToProps)(PostForm);

和PostContainer.js

import { connect } from 'react-redux';
import Post from './Post';
import { fetchFromApi } from '../reducers/postReducers';

const mapStateToProps = state => ({
  posts: state.posts,
});

const mapDispatchToProps = dispatch => ({
  fetchPosts: () => dispatch(fetchFromApi()),
  // sendPostData: (id, title, body) => dispatch(sendPost({ id, title, body })),
});

export default connect(mapStateToProps, mapDispatchToProps)(Post);

和我的减速器

import Axios from 'axios';

const reducerName = 'posts';
const createActionName = name => `/${reducerName}/${name}`;

/* action type */

const FETCH_POSTS = createActionName('FETCH_POSTS');
const SUBMIT_POST = createActionName('SUBMIT_POST');

/* action creator */
export const fetchStarted = payload => ({ payload, type: FETCH_POSTS });
export const submitPost = payload => ({ payload, type: SUBMIT_POST });

/* thunk */
export const fetchFromApi = () => {
  return (dispatch, getState) => {
    Axios.get('https://jsonplaceholder.typicode.com/posts?_limit=5').then(
      res => dispatch(fetchStarted(res.data))
      // console.log('res', res)
      // console.log('res data', res.data)
    );
  };
};

export const sendPost = (postId, postTitle, postBody) => {
  return (dispatch, getState) => {
    Axios.post('https://jsonplaceholder.typicode.com/posts', {
      id: postId,
      title: postTitle,
      body: postBody,
    }).then(res => {
      dispatch(submitPost(res.data));
    });
  };
};

/* reducer */
export default function reducer(state = [], action = {}) {
  switch (action.type) {
    case FETCH_POSTS:
      return action.payload;
    case SUBMIT_POST: {
      return {
        ...state,
        data: action.payload,
      };
    }
    default:
      return state;
  }
}

现在,我的console.logs显示我的所有数据都未定义。不知道我想念的是什么,但是我解决不了。

这也是我的stro.js

import { combineReducers, applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';

import postReducer from './reducers/postReducers';

const initialState = {
  posts: {
    data: {},
  },
};

const reducers = {
  posts: postReducer,
};

Object.keys(initialState).forEach(item => {
  if (typeof reducers[item] == 'undefined') {
    reducers[item] = (state = null) => state;
  }
});

const combinedReducers = combineReducers(reducers);

const store = createStore(
  combinedReducers,
  initialState,
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;

1 个答案:

答案 0 :(得分:0)

您的PostForm元素使用道具titlebody,但是您使用PostForm的地方不会向其发送body或{{1 }}属性。

我不知道您的特定用例,但是在React / Redux中,有两种方法可以将属性发送到元素:

title

或者通过使用Redux连接器,mapStateToProps函数,并返回与'body'和'title'键相匹配的对象,该键与Redux存储中的内容相匹配