简体   繁体   中英

How to call an action from a component without connecting it to the redux store?

I have a Cards component which takes in the props from the UserPosts component(which is connected to the store) and displays cards. Cards is not connected to the redux store and I want to dispatch an action in the handleDelete function. How can I do that?

import React, { Component } from "react"

class Cards extends Component {

  handleDelete = (id) => {

  }

  render() {
    const { title, description } = this.props.post
    const { postId } = this.props.post._id 
    return (
      <div className="card">
        <div className="card-content">
          <div className="media">
            <div className="media-left">
              <figure className="image is-48x48">
                <img
                  src="https://bulma.io/images/placeholders/96x96.png"
                  alt="Placeholder image"
                />
              </figure>
            </div>
            <div className="media-content" style={{border: "1px grey"}}>
              <p className="title is-5">{title}</p>
              <p className="content">{description}</p>
              <button className="button is-success">Edit</button>
              <button onClick={this.handleDelete(postId)} className="button is-success">Delete</button>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Cards

UserPosts component which passes the props

      <div>
        {userPosts &&
          userPosts.map(post => {
            return <Cards key={post._id} post={post} />
          })}
      </div>
    ```

You can use the global store and directly call dispatch method. Not recommended. Hard to maintain and debug.

import { createStore } from 'redux'
const store = createStore(todos, ['Use Redux'])
// Dont create new one, use the one created in root

function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text
  }
}

store.dispatch(addTodo('Read the docs'))
store.dispatch(addTodo('Read about the middleware'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM