这是一个非常基本的应用程序,用于列出github api中用户的存储库。我的控制台日志在reducer内部被调用,所以我知道它已经被击中,但是我的新状态从未被传递给更新组件props。
我对react-native较新,但是已经使用React和redux已有一段时间了。我以为这是一个特定于反应的问题,但是对于我一生,我无法弄清楚为什么我的道具没有更新。
此外,可能需要注意的是,如果我在create-react-app中运行相同的代码(我的动作,reducer,存储,连接和映射功能),它将按预期运行。它发出请求并照常返回新状态。
任何建议将不胜感激。
actions.js
import Axios from 'axios';
export const REQUEST_POSTS = 'REQUEST_POSTS';
export const RECEIVE_POSTS = 'RECEIVE_POSTS';
export const requestPosts = () => ({
type: REQUEST_POSTS,
});
export const receivedPosts = json => ({
type: RECEIVE_POSTS,
payload: json,
});
export function getData() {
return (dispatch) => {
dispatch(requestPosts());
return Axios('https://api.github.com/users/angular/repos')
.then(
response => response.data,
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
});
};
}
reducer.js
const initialState = {
loading: false,
repos: [],
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case REQUEST_POSTS:
console.log('REQUEST_POSTS');
return { ...state, loading: true };
case RECEIVE_POSTS:
console.log('RECIEVE_POSTS');
return {
...state, repos: action.payload.data, loading: false,
};
default:
return { ...state };
}
};
export default reducer;
RepoList.js
import { Text } from 'react-native';
import styled from 'styled-components/native';
import { connect } from 'react-redux';
import { getData } from '../../actions';
const Container = styled.View`
padding: 16px;
margin-top: 50px;
flex: 1;
align-items: center;
`;
const H1 = styled.Text`
font-weight: bold;
font-size: 40px;
`;
class RepoList extends Component {
componentDidMount() {
console.log('component did mount');
this.props.getData();
}
render() {
console.log('PROPS:', this.props);
const myList = this.props.repos.map(repo => <Text key={repo.id}>{repo.name}</Text>);
return (
<Container>
<H1>REPOS</H1>
{
this.props.loading
&& <H1>Loading...</H1>
}
{myList}
</Container>
);
}
}
const mapStateToProps = (state) => {
return {
repos: state.repos,
loading: state.loading,
};
};
const mapDispatchToProps = {
getData,
};
export default connect(mapStateToProps, mapDispatchToProps)(RepoList);
App.js
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import styled from 'styled-components/native';
import reducer from './src/reducers';
import RepoList from './src/components/RepoList';
const store = createStore(
reducer,
applyMiddleware(thunk),
);
const Wrapper = styled.View`
flex: 1;
align-items: center;
justify-content: center;
background-color: lightblue;
`;
export default class App extends Component {
render() {
return (
<Provider store={store}>
<Wrapper>
<RepoList />
</Wrapper>
</Provider>
);
}
}
答案 0 :(得分:0)
您是否在组件中得到“未定义”的仓库? 如果是,则在减速器中应返回action.payload而不是action.payload.data
case "RECEIVE_POSTS":
console.log("RECIEVE_POSTS");
return {
...state,
repos: action.payload.data,
loading: false
};