【发布时间】:2019-09-14 04:38:48
【问题描述】:
我正在移植一个 React 应用程序以使用 Redux。我可以看到该操作正在触发单击事件,但是当我将 console.log 添加到减速器中的操作时,我看到了一个未定义的值。
我正在使用 Redux thunk,因为我正在使用 fetch API 获取 JSON 数据。
generateQuote 操作应该返回一个新的报价。
我做的有什么明显错误的吗?
reducers/quotes.js
const defaultState =
{ quote: 'Hello World',
name: 'Me',
email: 'foo@bar.com',
date: Date(Date.now()),
generatedQuotes: []
}
const quotes = (state = defaultState, action) => {
switch(action.type) {
case GENERATE_QUOTE :
console.log(action.payload)
return { ...state, quotes: action.payload, date: action.date }
case DELETE_QUOTE :
return {
generatedQuotes: [...state.generatedQuotes.filter(quote => quote !== action.payload)]}
case SHARE_QUOTE :
return state;
default:
return state;
}
}
export default quotes;
actions/index.js
export const generateQuote = () => dispatch => {
const randomNum = (Math.floor(Math.random() * (500 - 1)) + 1);
fetch(`https://jsonplaceholder.typicode.com/comments?id=${randomNum.toString()}`)
.then(res => res.json())
.then(data => {
return
dispatch( {
type: GENERATE_QUOTE,
payload: data[0],
date: Date(Date.now())
})
})
}
Quote.js(组件)
/* eslint-disable react/require-default-props */
/* eslint-disable react/button-has-type */
/* eslint-disable react/jsx-filename-extension */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const Quote = ({quote, author, email, date, generateQuote, shareQuote}) => {
return (
<div className="box">
<p>
<strong>Quote:</strong>
{' '}
{quote}
</p>
<p>
<strong>Author:</strong>
{' '}
{author}
</p>
<p>
<strong>Email:</strong>
{' '}
{email}
</p>
<p>
<strong>Date:</strong>
{' '}
{date}
</p>
<br />
<div className="buttons">
<button className="button is-primary is-small" onClick={generateQuote}>New Quote</button>
<button className="button is-success is-small" onClick={shareQuote}>Tweet Quote</button>
</div>
</div>
);
};
Quote.propTypes = {
quote: PropTypes.string,
author: PropTypes.string,
email: PropTypes.string,
date: PropTypes.string,
generateQuote: PropTypes.func,
shareQuote: PropTypes.func,
};
const mapStateToProps = state => {
const { quote, author, email, date} = state;
};
const mapDispatchToProps = dispatch => {
return {
generateQuote: () => dispatch({type: 'GENERATE_QUOTE'}),
shareQuote: () => dispatch({type: 'SHARE_QUOTE'})
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Quote);
【问题讨论】:
-
您是否在
generateQuote操作中登录了data[0]? -
我确实尝试过控制台日志记录
data[0],但它没有返回任何内容。我想知道这是否意味着该动作实际上并未被调度?我现在才刚刚学习 Redux,所以我仍在努力掌握一切如何协同工作的窍门。 -
这可能意味着您的 api 调用没有返回您期望的结果。
-
这很奇怪。我使用本地状态进行了完全相同的 API 调用。如果您在这里查看 generateQuote,我会做几乎相同的事情。 github.com/fendermaniac/random-quote-machine-react/blob/master/…
标签: reactjs redux fetch redux-thunk