【发布时间】:2017-01-16 23:27:16
【问题描述】:
我希望用户能够在输入框中输入文本,并基于此搜索 api。我正在使用redux 和redux-thunk。我不确定如何将作为参数输入的文本传递给 API 调用。
如果我不使用 redux 和 thunk,我会将组件的状态设置为
this.state = {
movie: ''
}
然后在input type=text 上,我将使用e.target.value 更新movie 值onChange。 react与redux一起使用时应该采取什么方法?
我的代码如下所示。
import React, {Component} from 'react';
import {render} from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider, connect} from 'react-redux';
import thunk from 'redux-thunk';
import axios from 'axios';
function reducer(state = 0, action) {
switch (action.type) {
case 'GET_MOVIE':
return action.data;
default:
return state;
}
}
const store = createStore(
reducer,
applyMiddleware(thunk)
);
class App extends Component {
getMovie(){
this.props.getMovie();
}
render() {
return(
<div>
<input type='text'>
<input type='submit' onClick={this.props.getMovie}>
</div>
)
}
}
function getMovie(movie){
return function(dispatch) {
axios.get('http://www.omdbapi.com/?t=' + movie)
.then(function(data){
dispatch(resolvedGetMovie(data.data));
})
}
}
function resolvedGetMovie(data){
return {
type: '
GET_MOVIE ',
data: data
}
}
function mapStateToProps(state) {
return {
movie: state
}
}
function mapDispatchToProps(dispatch) {
return {
getMovie : () => dispatch(getMovie())
}
}
const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);
render(
<Provider store={store}>
<ConnectedApp />
</Provider>,
document.getElementById('root')
)
【问题讨论】:
标签: reactjs redux react-redux redux-thunk