我是 React Native 和 Redux 的新手,试图调用一个函数,但它给了我一个错误:
this.prop.getMovieTree is undefined.
当我双击 getmovietree 时,它会将我重定向到正确的功能。但它在运行时出错并使我的应用程序崩溃。当我 console.log(this.props)
打印定义的值但是当我打印 console.log(this.props.getMovieTree()) 时打印未定义。
//在 App.js 中:
import {getMovieTree} from './src/actions/RestActions'
export class App extends Component {
static propTypes = {
getMovieTree: PropTypes.func,
};
constructor(props) {
super(props)
}
componentWillMount()
{
this.props.getMovieTree();//at this line getting error: getmovietree() is undefined
}
}
const mapStateToProps = state => {
const { movieList } = state;
return {movieList};
};
export default connect(mapStateToProps,getMovieTree )(App);
//在 RestAction.js 文件中:
import {MAGENTO_GET_MOVIE_TREE} from './types'
import {magento} from '../magento'
export const getMovieTree = () => {
return async dispatch => {
try {
const customer = await magento.getMovieTreeCall();
dispatch({
type: MAGENTO_GET_MOVIE_TREE,
payload: customer
});
} catch (error) {
console.log(error);
}
};
};
//在 Index.js 中:
export default magento => {
return{
getMovieTreeCall : () => {
return new Promise((resolve, reject) => {
// const path = '/V1/AppVersion/';
magento
.send()
.then(data => {
resolve(data);
})
.catch(e => {
console.log(e);
reject(e);
});
});
},
};
};
In magento/index.js:
class Magento {
send(){
fetch("https://api.themoviedb.org/3/movie/now_playing?api_key=55957fcf3ba81b137f8fc01ac5a31fb5&language=en-US")
.then(response => response.json())
.then((responseJson) => {
return response.json()
// this.setState({
// loading: false,
// dataSource: responseJson.results
// })
})
.catch(error => console.log(error))
}
}
export const magento = new Magento();
最佳答案
- 首先,在 Magento 类中,您应该使用 await 或 Promise 来处理异步任务。方法应该是这样的:
async send(){ await fetch("https://api.themoviedb.org/3/movie/now_playing?api_key=55957fcf3ba81b137f8fc01ac5a31fb5&language=en-US") .then(response => response.json()) .then((responseJson) => { return response.json() // this.setState({ // loading: false, // dataSource: responseJson.results // }) }) .catch(error => console.log(error)) } }
- Then you should map dispatch to props and then connect it to component :
const mapStateToProps = state => ({ getMovieTree: state.getMovieTree })
//OR
const mapDispatchToProps = dispatch => {
return {
getMovieTree: () => dispatch({ }) ///your desired action
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
在这种情况下,我们不需要 mapDispatchToProps,您可以轻松地从 props 调用 getMovieTree
。 connect() 的第二个参数是 mapDispatchProps 并且可以像这样取消定义。
export default connect(mapStateToProps)(App);
关于javascript - 获取类型错误 :this. props.getMovieTree 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57254852/