【问题标题】:How to call an action from a component without connecting it to the redux store?如何在不将组件连接到 redux 存储的情况下从组件调用操作?
【发布时间】:2020-03-29 12:23:29
【问题描述】:

我有一个Cards 组件,它从UserPosts 组件(连接到商店)中获取道具并显示卡片。 Cards 未连接到 redux 存储,我想在 handleDelete 函数中调度一个操作。我该怎么做?

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 传递 props 的组件

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

【问题讨论】:

  • 为什么不直接连接??
  • 除了在这个组件中调度之外,我不需要商店里的任何东西。不知道能不能连上?
  • 没关系,你给空白的mpStateToProp回调。但是,我有答案,请检查是否为你工作。
  • 永远不要直接与商店互动。 connect 组件或在函数组件中使用useDispatch 钩子
  • 好吧,我刚刚使用了store.dispatch(deletePosts(id),我刚刚去刷新了Cards 组件,它一直在获取所有帖子。我知道发生了什么。看起来它陷入了无限循环哈哈。

标签: javascript reactjs redux


【解决方案1】:

可以使用全局存储,直接调用dispatch方法。不建议。难以维护和调试。

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'))

【讨论】:

猜你喜欢
  • 2018-08-28
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 2020-11-01
  • 2020-01-06
  • 2021-01-01
相关资源
最近更新 更多