我一直遵循关于Udemy的完整的本机和redux指南,尽管有一个发球台,但仍有这部分。我的LibraryList组件仍然被调用两次。 可能是什么问题?
LibraryList.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
class LibraryList extends Component {
render() {
console.log(this.props);
return;
}
}
function mapStateToProps(state) {
return {
libraries: state.libraries
};
}
export default connect(mapStateToProps)(LibraryList);
App.js
import React from 'react';
import { View } from 'react-native';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './reducers';
import { Header } from './components/common';
import LibraryList from './components/LibraryList';
const App = () => {
return (
<Provider store={createStore(reducers)}>
<View>
<Header headerText='Tech Stack' />
<LibraryList />
</View>
</Provider>
);
};
export default App;
LibraryReducer.js
import data from './LibraryList.json';
export default () => data;
reducers文件夹中的index.js
import { combineReducers } from 'redux';
import LibraryReducer from './LibraryReducer';
export default combineReducers({
libraries: LibraryReducer
});
LibraryList.json
[
{"id": 0,
"title": "Webpack",
"description": "Webpack is a module bundler. It packs CommonJs/AMD modules i. e. for the browser. Allows to split your codebase into multiple bundles, which can be loaded on demand."
},
....
]
预期结果:console.log(this.props)运行一次并返回库
实际结果:它运行两次
答案 0 :(得分:1)
I had a similar problem with one of my projects.
In LibraryList.js
instead of extending Component
use PureComponent
. PureComponents won't call the render function if the state and the props have not changed, since it integrates a simple check in the shouldComponentUpdate
method. https://reactjs.org/docs/react-api.html#reactpurecomponent
You could always implements your own shouldComponentUpdate
method with a React Component
instead of using the PureComponent
. You'll need to be careful when implement the shouldComponentUpdate
method with Redux, you may create more bugs. https://redux.js.org/faq/react-redux#why-isn-t-my-component-re-rendering-or-my-mapstatetoprops-running
When I tried your example on Android and iOS, I wasn't able to replicate your issue, it only returned once.