React Redux从特定索引处的数组中删除项目

时间:2019-04-30 01:26:15

标签: reactjs redux

我正在尝试通过访问要映射到各个组件的数组中对象的ID来删除数组中的项目。

我很确定我的reducer配置正确,但是我无法将对象的id传递给操作。当我console.log操作有效负载时,我得到Class {dispatchConfig: {…}, _targetInst: FiberNode, _dispatchListeners: ƒ, _dispatchInstances: FiberNode, nativeEvent: MouseEvent, …}

这是代码

操作:

  console.log(id)
  return {
    type: DELETE_QUOTE,
    payload: id
  }
} 

减速器:

        return {
          ...state,
          generatedQuotes: state.generatedQuotes.filter(quote=>quote.id !== action.payload.id)
        }

容器组件:

{this.props.generatedQuotes.map((item, i) => 
                <div className="column is-half" key={i}>
                <QuoteCard
                  author={item.name} 
                  quote={item.quote} 
                  email={item.email} 
                  date={item.date}
                  id={item.id}
                  deleteQuote={this.props.deleteQuote}
                />
                </div>
          )}
容器组件中的

mapDispatchToProps:

const mapDispatchToProps = dispatch => {
  return {
    generateQuote: () => dispatch(generateQuote()),
    deleteQuote: id => dispatch(deleteQuote(id))
  };
}

代表性组件:

const QuoteCard = ({author, email, date, quote, id, deleteQuote}) => {
  return (
    <div className="box" key={date}>
      <article className="media">
        <div className="media-left">
          <figure className="image is-128x128">
            <img src="https://bulma.io/images/placeholders/128x128.png" alt="Mock" />
          </figure>
        </div>
        <div className="media-content">
          <div className="content">
            <p>
              <strong>{author}</strong>
              <small>{email}</small>
              <br />
              <small><em>{date}</em></small>
              <br />
              {quote}
            </p>
          </div>
        </div>
      </article>
      <br />
      <div className="buttons">
        <button className="button is-success is-small" onClick={() => window.open(`https://twitter.com/intent/tweet?text="${quote}" Quote by: ${author}`)}>Tweet Quote</button>
        <button className="button is-danger is-small" onClick={(id) => deleteQuote(id)}>Delete Quote</button>
      </div>
    </div>
  );
};

1 个答案:

答案 0 :(得分:3)

您的idaction.payload,所以

return {
  ...state,
  generatedQuotes: state.generatedQuotes.filter(quote=> quote.id !== action.payload)
};