我有一个组件可以将动作绑定到像这样的道具
我没有在handleButtonclick函数中包含完整的api调用代码,以避免不必要的代码。
class LogInComponent extends Component {
static contextTypes = {
router: PropTypes.object.isRequired
}
handleLoginButtonClick() {
let token;
$.ajax(settings).done((response) => {
token = JSON.stringify(response.auth_token)
this.props.setAuthToken(token);
this.context.router.push('/app')
});
}
render(){
return (
<div className="LoginPage">
<button onClick={this.handleLoginButtonClick.bind(this)}>login</button>
</div>
);
}
}
const mapStateToProps = (state)=> ({
auth_token: state.Data.auth_token
})
function matchDispatchToProps(dispatch) {
return bindActionCreators({setAuthToken: actions.setAuthToken}, dispatch);
}
export default connect(mapStateToProps, matchDispatchToProps)(LogInComponent);
这是我的行动和减速器所在的地方:
import fetch from 'isomorphic-fetch'
const INITIAL_STATE = {
list: [],
selectedRows: [],
currentItem: {},
auth_token:null
}
const FETCH_LIST = 'FETCH_LIST'
const fetchList = ()=> (dispatch)=> {
dispatch({type: FETCH_LIST});
fetch('/api/items?n=50')
.then(resp => resp.json())
.then(data => dispatch(fetchListSuccess(data)))
.catch(err => dispatch(fetchListError(err)))
}
const FETCH_LIST_SUCCESS = 'FETCH_LIST_SUCCESS'
const fetchListSuccess = (list)=> {
console.log('Received List: ', list)
return {
type: FETCH_LIST_SUCCESS,
list
}
}
const FETCH_LIST_ERROR = 'FETCH_LIST_ERROR'
const fetchListError = (error)=> {
console.error(error)
return {
type: FETCH_LIST_ERROR,
error: error.message
}
}
const SELECT_ROWS = 'SELECT_ROWS'
const selectRows = (ids)=> {
return {
type: SELECT_ROWS,
ids
}
}
const SET_AUTH_TOKEN = 'SELECT_ROWS'
const setAuthToken = (token)=> {
return {
type: SET_AUTH_TOKEN,
payload: token
}
}
const SET_CURRENT_ITEM = 'SET_CURRENT_ITEM'
const setCurrentItem = (item)=> {
return {
type: SET_CURRENT_ITEM,
item
}
}
export const actions = {
fetchList,
selectRows,
setCurrentItem,
setAuthToken
}
export default function DataReducer(state = INITIAL_STATE, action){
switch(action.type){
case FETCH_LIST:
return {...state, isLoading: true }
case FETCH_LIST_SUCCESS:
return { ...state, isLoading: false, list: [...action.list] }
case FETCH_LIST_ERROR:
return {...state, isLoading: false, hasError: action.error }
case SELECT_ROWS:
return {...state, selectedRows: [...action.ids]}
case SET_CURRENT_ITEM:
return {...state, currentItem: {...action.item}}
case SET_AUTH_TOKEN:
return {...state, auth_token:action.payload}
default:
return state
}
}
我哪里错了?