【发布时间】:2019-04-24 19:30:15
【问题描述】:
我已经学习了 React 并且我已经学会了使用 Context API,但是我听说有一个“新的上下文 API”,因为我已经通过一种旧课程(2017 年末)学习了 React,所以我没有不知道我使用的是新的还是旧的 Context API。 另外我刚刚发现了 Redux,它看起来和我使用的几乎完全一样,所以 Redux 和 Context API 到底是一样的吗?
看看我的代码:
这里是我的 context.js:
import React, {Component} from 'react'
const Context = React.createContext();
const reducer = (state, action) => {
switch(action.type) {
case 'DELETE_CONTACT' :
return {
...state,
contacts: state.contacts.filter(contact =>
contact.id !== action.payload)
};
default:
return state;
}
}
export class Provider extends Component {
state = {
contacts : [
{
id: 1,
nom : 'John Doe',
email : 'john@gmail.com',
tel : "555-555-5555"
},
{
id: 2,
nom : 'John Doe',
email : 'john@gmail.com',
tel : "555-555-5555"
},
{
id: 3,
nom : 'Hugo Doe',
email : 'john@gmail.com',
tel : "555-555-5555"
}
],
dispatch: action => {
this.setState(state => reducer(state,action))
}
}
render() {
return (
<Context.Provider value={{
state: this.state,
sayHello: () => console.log("Hello World")
}}>
{this.props.children}
</Context.Provider>
)
}
}
export const Consumer = Context.Consumer;
请注意,我使用的是“Reducer”和“Dispatch”,它们甚至不在“Context”的 React 官方文档中:(?
你也可以看看我的“消费者”:
import React, { Component } from 'react'
import Contact from './Contact'
import {Consumer} from '../context'
export default class Liste extends Component {
render() {
return (
<Consumer>
{value => {
return(
<React.Fragment>
{value.state.contacts.map(contact => (
<Contact
key={contact.id}
id={contact.id}
nom={contact.nom}
email={contact.email}
tel={contact.tel}
/>
))}
</React.Fragment>
)
}}
</Consumer>
)
}
}
Context 和 React 之间的具体区别是什么? 我可以将 Reducer 与 Context 一起使用吗? 我使用的是旧上下文还是新上下文? 为什么 Context 适合小应用,Redux 适合大应用?
我无法明确回答的问题太多了,有大量文章和视频的说法正好相反。
有好心人能启发我吗?
【问题讨论】: