我正在尝试使用redux表单将字段传递给动作创建者,该动作创建者使用该字段结果命中api。结果应该发送回同一个组件并在搜索输入字段下呈现。这是我的动作创作者
export function getStock({ticker_symbol}){
console.log(ticker_symbol)
return function(dispatch) {
axios.get(`https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${ticker_symbol}&interval=1min&apikey=5QP2C2R2YCZ71HDB&datatype=json`, {
headers: { authorization: localStorage.getItem('token')}
})
.then(res => {
console.log(res.data["Time Series (1min)"])
dispatch({
type: GET_STOCK,
payload: res.data
})
}).catch(res => {
dispatch(authError(res.error))
});
}
}
这里是减速器
import {
FETCH_MESSAGE,
GET_STOCK
} from '../actions/types';
export default function(state = {}, action){
switch(action.type) {
case FETCH_MESSAGE:
return {...state, message: action.payload};
case GET_STOCK:
return {...state, stock: action.payload,
stockDataLoaded: false};
}
return state;
}
这里是具有表单的组件,并且假设获取呈现信息。控制台日志为我提供了正确的数据。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import * as actions from '../actions';
class Feature extends Component{
componentWillMount(){
this.props.fetchMessage();
}
handleFormSubmit({ ticker_symbol }){
console.log( ticker_symbol );
this.props.getStock({ticker_symbol});
}
render(){
const { handleSubmit, fields: { ticker_symbol }} = this.props;
return (
<div>
<form onSubmit={ handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<label> Ticker Symbol: </label>
<input {...ticker_symbol} className="form-control" />
</fieldset>
<button action="submit" className="btn btn-primary"> Get Quote </button>
</form>
<h1></h1>
</div>
);
}
}
function mapStateToProps(state){
console.log(state);
return { message: state.stock.message,
stock: state.stock.stock};
}
export default reduxForm({
form: 'getstock',
fields: ['ticker_symbol']
}, mapStateToProps, actions)(Feature);
以下是页面/控制台的屏幕截图
我希望结果显示在股票代码
下答案 0 :(得分:0)
回应你的评论;
任何依赖于它的状态的组件都需要使用getInitialState
生命周期钩子初始化state属性;
getInitialState() {
return {
};
}
如果您只想初始化状态对象,可以将其全部留空,或者可以使用默认的起始值填充它。