简体   繁体   中英

How to set a variable to a context supplied value (React)

I am trying to set a variable to a array value in the context of my react app. The approach I am using worked perfectly when I used it in a function but I am refactoring to export that function as a class component and now am returning an object that isn't even in my state. Any thoughts?

The variable I am trying to set in 'FilterNotes.js' component:

const notes = [<MyContext.Consumer>{context => context.state.notes}</MyContext.Consumer>];

What the output should be:

[
  {
    "id": "cbc787a0-ffaf-11e8-8eb2-f2801f1b9fd1",
    "name": "Dogs",
    "modified": "2019-01-03T00:00:00.000Z",
    "folderId": "b0715efe-ffaf-11e8-8eb2-f2801f1b9fd1",
    "content": "Laborum possimus aperiam. Culpa eos in. Excepturi commodi corporis. Distinctio quo ipsum aperiam et itaque ut quod ut. Modi corporis soluta et deleniti ut. Voluptatibus corrupti aut quia rerum.\n \rOdio ea cupiditate dicta. Aut quia consequatur reprehenderit est sint est fuga illum ex. Adipisci voluptatibus in enim expedita distinctio sint harum dolorem dolor.\n \rQuia accusantium dicta voluptatum reiciendis. Voluptatem illum iusto animi voluptatem fugiat adipisci dolore quia. Sunt fuga autem et qui quo. Consequatur perferendis omnis quisquam repellat voluptas vero deserunt."
  },
...
]

What I am getting as an output:

$$typeof: Symbol(react.element)
key: null
props: {children: ƒ}
ref: null
type: {$$typeof: Symbol(react.context), _context: {…}, _calculateChangedBits: null, …}
_owner: FiberNode {tag: 1, key: null, elementType: ƒ, type: ƒ, stateNode: FilterNotes, …}
_store: {validated: false}
_self: FilterNotes {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternalFiber: FiberNode, …}
_source: {fileName: "/Users/ryancarville/Desktop/FED_Projects/noteful/src/FilterNotes/FilterNotes.js", lineNumber: 8}
__proto__: Object

Component:

export default class FilterNotes extends Component {
    render() {
        const notes = [<MyContext.Consumer>{context => context.state.notes}</MyContext.Consumer>];

        console.log(notes);
        const folderId = this.props.folderId;
        console.log(folderId);
        const notesFiltered = notes.filter(note => note.folderId === { folderId });

        console.log(notesFiltered);
        return notesFiltered.map((n, i) => {
            return (
                <MyContext.Consumer>
                    {context => (
                        <div key={i}>
                            <li key={n.id}>
                                <Link to={`/notes/${n.id}`}>{n.name}</Link>
                                <br />
                                <br />
                                Date Modified: {n.modified}
                            </li>

                            <button
                                type='button'
                                className='deleteNoteBTN'
                                onClick={() => context.state.deleteNote(`${n.id}`)}>
                                Delete Note
                            </button>
                        </div>
                    )}
                </MyContext.Consumer>
            );
        });
    }
}

Context value isn't available outside Consumer callback function scope, this is the reason why a callback is used there.

All code that depends on context value should be placed inside a function:

export default class FilterNotes extends Component {
    render() {
        return (
            <MyContext.Consumer>{context => {
                const notes = context.state.notes;
                const folderId = this.props.folderId;
                const notesFiltered = notes.filter(note => note.folderId === { folderId });

                return notesFiltered.map((n, i) => (
                    <div key={i}>
                    ...

Consumer can be omitted if contextType is used but this restricts a component to use a single context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM