我正在练习redux传奇。我见过所有类似的问题,但他们没有帮助我。
实际上,我的动作是在抓取,从url获取数据并且状态在变化,但是没有映射到道具。
我的代码
Home.js
class Home extends Component {
render() {
console.log(this.props);
return (
<View style={{ justifyContent: "center", alignItems: "center", flex: 1 }}>
<Text>Welcome to Dog Saga</Text>
<Button title={"Show Dog"} onPress={this.props.onRequestDog} />
{this.props.loading ? (
<ActivityIndicator size="large" color={"red"} />
) : this.props.error ? (
<Text>Error Occured</Text>
) : (
<Image
source={{ uri: this.props.url }}
style={{ width: 100, height: 100 }}
/>
)}
</View>
);
}
}
const mapStateToProps = state => {
return {
url: state.url,
loading: state.loading,
error: state.error
};
};
const mapDispatchToProps = dispatch => ({
onRequestDog: () => dispatch(requestDog())
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(Home);
apiReducer.js
import {
API_CALL_REQUEST,
API_CALL_SUCCESS,
API_CALL_FAILURE
} from "../actions/actionTypes";
const initialState = {
url: "",
loading: false,
error: false
};
const apiReducer = (state = initialState, action) => {
switch (action.type) {
case API_CALL_REQUEST:
return {
...state,
url: "",
loading: true,
error: false
};
case API_CALL_SUCCESS:
return {
...state,
url: action.url,
loading: false,
error: false
};
case API_CALL_FAILURE:
return {
...state,
url: "",
loading: false,
error: true
};
default:
return state;
}
};
export default apiReducer;
apiSaga.js
import { takeEvery, call, put, all } from "redux-saga/effects";
import axios from "axios";
import * as types from "../actions/actionTypes";
import {
requestDog,
requestDogSuccess,
requestDogError
} from "../actions/actions";
//watcher saga, watches for actions dispatached to the store , starts worker saga
export default function* watcherSaga() {
yield takeEvery(types.API_CALL_REQUEST, workerSaga);
//yield takeLatest(API_CALL_REQUEST, workerSaga);
}
// function that makes the api request and returns a Promise for response
function fetchDog() {
return axios({
method: "get",
url: "https://dog.ceo/api/breeds/image/random"
});
}
// worker saga: makes the api call when watcher saga sees the action
export function* workerSaga() {
try {
//yield put(requestDog());
const response = yield call(fetchDog);
// dispatch a success action to the store with the new dog
yield put(requestDogSuccess(response.data));
} catch (error) {
// dispatch a failure action to the store with the error
yield put(requestDogError());
}
}
问题
RequestDog的抓取效果很好,图像url的检索效果也很好,但是存储区中已更改的状态未显示任何效果成分。表示图像未加载。
图片会告诉您发生了什么事。
答案 0 :(得分:1)
也许您错过了映射中的apiReducer
状态键:
const mapStateToProps = state => {
return {
url: state.apiReducer.url,
loading: state.apiReducer.loading,
error: state.apiReducer.error
};
};
或简单地:
const mapStateToProps = state => state.apiReducer;